Chapter 6 影像排列
def : 新建一個函數
isinstance : 比對資料格式
hstack : 水平排列
vstack : 垂直排列
import cv2
import numpy as np
#------Part1
'''
img = cv2.imread("lena.png")
imgHor = np.hstack((img,img)) # 2 range horizontal in a window
imgVer = np.vstack((img,img)) # 2 range vertical in a window
img4 = np.vstack((imgHor,imgHor)) # 4 images in a window
cv2.imshow("Horizontal Images",imgHor)
cv2.imshow("Vertical Images",imgVer)
cv2.imshow("4 Images",img4)
'''
#------Part2
def stackImages(scale,imgArray):
rows = len(imgArray) # how many rows(有幾行)
cols = len(imgArray[0]) # how many columns(有幾列)
rowsAvailable = isinstance(imgArray[0], list) # check if "imgArray" is list
width = imgArray[0][0].shape[1] # get the first image width size
height = imgArray[0][0].shape[0] #get the first image height size
if rowsAvailable:
for x in range ( 0, rows):
for y in range(0, cols):
if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:
# if the first image size equal to another one
imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)
# resize the images
else:
imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)
# resize the different size image to first image size.
if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)
# if the image is gray will change to BGR
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])
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("lena.png")
imgStack = stackImages(0.5,([img,img],[img,img]))
cv2.imshow("ImagesStack",imgStack)
cv2.waitKey(0)
No comments:
Post a Comment