OpenCV-Python 圖片簡單處理 & 拼接對比
阿新 • • 發佈:2020-07-26
import cv2 import numpy as np img = cv2.imread("Resources/The Legend of Zelda.jpg") kernel = np.ones((5, 5), np.uint8) # 卷積核 # 顏色空間轉換,轉換成灰度圖(注意是BGR而不是RBG) imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 平滑處理,高斯模糊, 高斯核的寬和高只能是奇數 imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 0) # 邊緣檢測, 實際也是採用了高斯模糊去除噪音並設定梯度閾值進行過濾 imgCanny = cv2.Canny(img, 150, 200) # 膨脹,可以適當增加迭代次數 imgDilated = cv2.dilate(imgCanny, kernel, iterations=1) # 侵蝕 imgEroded = cv2.erode(imgDilated, kernel, iterations=1) # 縮小到0.2倍並拼接 imgStack = stackImages(0.2, [[img, imgGray, imgBlur], [imgCanny, imgDilated, imgEroded]]) cv2.imshow("Image Stack", imgStack) cv2.waitKey(0)
其中stackImage函式的定義為
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): 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) 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]) 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
封裝了numpy中的vstack和hstack,方便使用
效果:
更多影象處理可參考官方文件:https://docs.opencv.org/master/d2/d96/tutorial_py_table_of_contents_imgproc.html