我将要使用Opencv绘制一些图像,为此,我想将图像粘合在一起。
想象一下,我有4张图片。最好的方法是将它们粘贴在2x2图像矩阵中。
a = img; a.shape == (48, 48)
b = img; b.shape == (48, 48)
c = img; c.shape == (48, 48)
d = img; d.shape == (48, 48)
现在,我使用np.reshape,该列表带有诸如[a,b,c,d]之类的列表,然后手动放置尺寸以获取以下内容:
np.reshape([a,b,c,d], (a.shape*2, a.shape*2)).shape == (96, 96)
当我有3张图片时,问题开始了。我有点想,我可以取列表长度的平方根,然后取上限值,这将得出2的方阵维数(
np.ceil(sqrt(len([a,b,c]))) == 2
)。然后,我必须将具有第一个元素尺寸的白色图像添加到列表中,然后我们就可以了。但是我认为必须有一种更简单的方法来完成绘制工作,这很可能已经在某处定义了。那么,如何轻松地将任意数量的平方矩阵组合成一个大的平方矩阵呢?
编辑:
我提出以下内容:
def plotimgs(ls):
shp = ls[0].shape[0] # the image's dimension
dim = np.ceil(sqrt(len(ls))) # the amount of pictures per row AND column
emptyimg = (ls[1]*0 + 1)*255 # used to add to the list to allow square matrix
for i in range(int(dim*dim - len(ls))):
ls.append(emptyimg)
enddim = int(shp*dim) # enddim by enddim is the final matrix dimension
# Convert to 600x600 in the end to resize the pictures to fit the screen
newimg = cv2.resize(np.reshape(ls, (enddim, enddim)), (600, 600))
cv2.imshow("frame", newimg)
cv2.waitKey(10)
plotimgs([a,b,d])
以某种方式,即使尺寸尚可,它实际上还会克隆更多图片:
因此,实际上,不是平方,而是以某种方式获得了图像的三次幂。虽然,例如
plotimg([a]*9)
给出一张图片的尺寸为44*3 x 44*3 = 144x144
,它对于9张图像应该正确吗? 最佳答案
这是我用于执行此类操作的代码段:
import numpy as np
def montage(imgarray, nrows=None, border=5, border_val=np.nan):
"""
Returns an array of regularly spaced images in a regular grid, separated
by a border
imgarray:
3D array of 2D images (n_images, rows, cols)
nrows:
the number of rows of images in the output array. if
unspecified, nrows = ceil(sqrt(n_images))
border:
the border size separating images (px)
border_val:
the value of the border regions of the output array (np.nan
renders as transparent with imshow)
"""
dims = (imgarray.shape[0], imgarray.shape[1]+2*border,
imgarray.shape[2] + 2*border)
X = np.ones(dims, dtype=imgarray.dtype) * border_val
X[:,border:-border,border:-border] = imgarray
# array dims should be [imageno,r,c]
count, m, n = X.shape
if nrows != None:
mm = nrows
nn = int(np.ceil(count/nrows))
else:
mm = int(np.ceil(np.sqrt(count)))
nn = mm
M = np.ones((nn * n, mm * m)) * np.nan
image_id = 0
for j in xrange(mm):
for k in xrange(nn):
if image_id >= count:
break
sliceM, sliceN = j * m, k * n
img = X[image_id,:, :].T
M[sliceN:(sliceN + n), sliceM:(sliceM + m)] = img
image_id += 1
return np.flipud(np.rot90(M))
示例:
from scipy.misc import lena
from matplotlib import pyplot as plt
img = lena().astype(np.float32)
img -= img.min()
img /= img.max()
imgarray = np.sin(np.linspace(0, 2*np.pi, 25)[:, None, None] + img)
m = montage(imgarray)
plt.imshow(m, cmap=plt.cm.jet)
关于python - 给定任意数量的较小平方矩阵来创建平方矩阵的算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21135279/