一、图像的截取
把图像当作数组处理即可(宽度, 高度, 通道数)。
import cv2
img = cv2.imread('./cat.jpg', cv2.IMREAD_COLOR)
subimg = img[0:800, 0:800]
cv2.imshow('title', subimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
二、颜色通道提取与合并
注意opencv中彩图为BGR图像,不是RGB。
import cv2
img = cv2.imread('./cat.jpg', cv2.IMREAD_COLOR)
b, g, r = cv2.split(img) #通道分离
img = cv2.merge((b, g, r)) #通道合并
#只保留R通道
subimg = img.copy()
subimg[:, :, 0] = 0
subimg[:, :, 1] = 0
cv2.imshow('R', subimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
#只保留G通道
subimg = img.copy()
subimg[:, :, 0] = 0
subimg[:, :, 2] = 0
cv2.imshow('G', subimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
#只保留B通道
subimg = img.copy()
subimg[:, :, 1] = 0
subimg[:, :, 2] = 0
cv2.imshow('B', subimg)
cv2.waitKey(0)
cv2.destroyAllWindows()
三、边界填充
replicate:复制法,复制最边缘像素
reflect:反射法,在两边进行复制
reflect_101:反射法,以最边缘像素为轴对称
wrap:外包装法
constant:常量法,常数填充
import cv2
img = cv2.imread('./cat.jpg', cv2.IMREAD_COLOR)
top_size, bottom_size, left_size, right_size = (50, 50, 50, 50)
replicate = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_WRAP)
constant = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_CONSTANT, value=0)
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(2, 3, 1)
plt.imshow(img, 'gray')
plt.title('ORIGINAL')
plt.subplot(2, 3, 2)
plt.imshow(replicate, 'gray')
plt.title('REPLICATE')
plt.subplot(2, 3, 3)
plt.imshow(replicate, 'gray')
plt.title('REFLECT')
plt.subplot(2, 3, 4)
plt.imshow(reflect101, 'gray')
plt.title('REFLECT101')
plt.subplot(2, 3, 5)
plt.imshow(wrap, 'gray')
plt.title('WRAP')
plt.subplot(2, 3, 6)
plt.imshow(constant, 'gray')
plt.title('CONSTANT')
plt.show()
四、图像的放缩
import cv2
img = cv2.imread('./cat.jpg', cv2.IMREAD_COLOR)
#缩放到指定大小
res = cv2.resize(img, (500, 300))
cv2.imshow('cat', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
#指定倍数缩放
res = cv2.resize(img, (0, 0), fx=0.5, fy=1.5)
cv2.imshow('cat', res)
cv2.waitKey(0)
cv2.destroyAllWindows()