Wednesday, August 5, 2020

Jul 27, 2020 日誌

學習如何使用opencv。Chapter 6 影像排列。

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

協同設計

2022 一開始, 將計算機程式與電腦輔助設計實習課程的期末報告導向 Github 倉儲的協同, 倉儲分別在 https://github.com/mdecourse/cp2021_final 與 https://github.com/mdecourse/cad2021_fin...