天天看點

python opencv建立固定大小的圖像 單或多通道

單通道

import cv2
import numpy as np

img = np.zeros((500, 500), np.uint8)
# 黑色
cv2.imshow('img', img)
# 淺灰色
img.fill(200)
cv2.imshow('img200', img)

image = np.zeros((400, 600),img.dtype)
print(image.shape)
cv2.imshow('image', image)
cv2.waitKey()      
python opencv建立固定大小的圖像 單或多通道
import cv2
import numpy as np

image = cv2.imread("cytu.png")
cv2.imshow('image',image)

# 方法一
h,w,c = image.shape
black = np.zeros((h,w,c),dtype = np.uint8)
cv2.imshow('black',black)


# 方法二
imgBlack = np.zeros_like(image)
cv2.imshow('imgBlack',imgBlack)


# 方法三
newImg = np.zeros(image.shape, dtype=np.uint8)
# newImg = np.zeros(image.shape, image.dtype)
cv2.imshow('newImg',newImg)
print(imgBlack.shape)
cv2.waitKey()      
import cv2
import numpy as np

# 建立彩色圖像(RGB)
# (1) 通過寬度高度值建立多元數組
height, width, channels = 400, 300, 3  # 行/高度, 列/寬度, 通道數
imgEmpty = np.empty((height, width, channels), np.uint8)  # 建立空白數組
imgBlack = np.zeros((height, width, channels), np.uint8)  # 建立黑色圖像 RGB=0
imgWhite = np.ones((height, width, channels), np.uint8) * 255  # 建立白色圖像 RGB=255


# (2) 建立相同形狀的多元數組
img1 = cv2.imread("flower.jpg", flags=1)  # flags=1 讀取彩色圖像(BGR)
imgBlackLike = np.zeros_like(img1)  # 建立與 img1 相同形狀的黑色圖像
imgWhiteLike = np.ones_like(img1) * 255  # 建立與 img1 相同形狀的白色圖像

# (3) 建立灰階圖像
imgGrayWhite = np.ones((height, width), np.uint8) * 255  # 建立白色圖像 Gray=255
imgGrayBlack = np.zeros((height, width), np.uint8)  # 建立黑色圖像 Gray=0
imgGrayEye = np.eye(width)  # 建立對角線元素為1 的機關矩陣