np.vstack()
按垂直方向(行顺序)堆叠数组构成一个新的数组
np.hstack()
按水平方向(列顺序)堆叠数组构成一个新的数组
可以把图片叠加展示
img = cv2.imread("Resources/majiang.JPG")
# imggray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#给图片缩小一下
img = cv2.resize(img,(0,0),None,0.3,0.3)
imgHor = np.hstack((img,img))
imgVer = np.vstack((img,img))
cv2.imshow("Horizontal",imgHor)
cv2.imshow("Vertical",imgVer)
cv2.waitKey(0)
# scale为传入的缩小放大值,imgArray为传入的图片数组
def stackImages(scale, imgArray):
rows = len(imgArray)
cols = len(imgArray[0])
# 判断是否为单图片
rowsAvailable = isinstance(imgArray[0], list)
width = imgArray[0][0].shape[1]
height = imgArray[0][0].shape[0]
if rowsAvailable:
for x in range(0, rows):
for y in range(0, cols):
# 判断图片xy是否和00图片一样大,如果一样大则按照原先尺度缩放,否则不变
if imgArray[x][y].shape[:2] == imgArray[0][0].shape[:2]:
imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
else:
imgArray[x][y] = cv2.resize(imgArray[x][y],
(imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale,
scale)
#判断图片有几个通道,shape0,1通道为长宽,2为颜色,如果没有颜色设置为灰度图
if len(imgArray[x][y].shape) == 2: imgArray[x][y] = cv2.cvtColor(imgArray[x][y],
cv2.COLOR_GRAY2BGR)
imageBlank = np.zeros((height, width, 3), np.uint8)
hor = [imageBlank] * rows
hor_con = [imageBlank] * rows
for x in range(0, rows):
#按水平方向(列顺序)堆叠数组构成一个新的数组
hor[x] = np.hstack(imgArray[x])
#hor垂直方向塞入
ver = np.vstack(hor)
else:
for x in range(0, rows):
if imgArray[x].shape[:2] == imgArray[0].shape[:2]:
imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)
else:
imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None, scale,
scale)
if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)
hor = np.hstack(imgArray)
ver = hor
return ver
展示效果
img = cv2.imread("Resources/majiang.JPG")
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
imgStack = stackImages(0.2, ([img, imgGray, img], [img, img, img]))
cv2.imshow("ImageStack", imgStack)
cv2.waitKey(0)