@Fu Xianjun. All Rights Reserved.
图像的加法运算、位运算都是比较基础的运算。但是,很多复杂的图像处理功能正是借助这些基础的运算来完成的。
在图像处理处理过程中,经常需要对图像进行加法运算。可以通过加号运算符“+”对图像进行加法运算,也可以通过cv.add()函数对图像进行加法运算。
1、图像类型转换
import cv2
import numpy as np
img1=cv2.imread("pig.jpg")
rgb = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)#图像类型转换函数
cv2.imshow("BGR",img1)
cv2.imshow("RGB",rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
2、图像对象rgb已经转换为rgb格式,如何将其转换回BGR格式
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
cv2.imshow("BGR2",bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()
3、将图像在BGR模式与GRAY模式之间转换
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
cv2.imshow("GRAY",gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
4、颜色通道分离
print(f"BGR图像的shape为{bgr.shape}")
print(f"GRAY图像的shape为{gray.shape}")
def Colorsplit(img):
(B,G,R) = cv2.split(img)#将BGR图像的颜色通道分离
cv2.imshow("blue",B)
cv2.imshow("green",G)
cv2.imshow("red",R)
cv2.waitKey(0)
cv2.destroyAllWindows()
Colorsplit(bgr)#将转换前的RGB图像颜色通道分离
bgr2 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.imshow("after",bgr2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Colorsplit(bgr2)#将转换后的RGB图像颜色通道分离
结论:GRAY转换为BRG颜色空间,各通道值相同
def Colorsplit(img):
(B,G,R) = cv2.split(img)#将BGR图像的颜色通道分离
cv2.imshow("blue",B)
cv2.imshow("green",G)
cv2.imshow("red",R)
cv2.waitKey(0)
cv2.destroyAllWindows()
Colorsplit(bgr)#将转换前的RGB图像颜色通道分离
bgr2 = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.imshow("after",bgr2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Colorsplit(bgr2)#将转换后的RGB图像颜色通道分离
结论:GRAY转换为BRG颜色空间,各通道值相同
5、图像对象rgb已经转换为HSV格式,如何将其转换回BGR格式
bgr3=cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR)#转换为HSV颜色空间
cv2.imshow("BGR",bgr3)
cv2.waitKey(0)
cv2.destroyAllWindows()
6、提取指定颜色
eg:(提取红色)
import cv2
import numpy as np
img2=cv2.imread("pig.jpg")
cv2.imshow("SRC",img2)
hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)#图像类型转换函数
cv2.imshow("HSV",hsv)
lowerb_hsv = np.array([156,43,46])#要识别颜色的下限
upperb_hsv = np.array([180,255,255])#要识别的颜色的上限
mask = cv2.inRange(hsv, lowerb_hsv, upperb_hsv)
cv2.imshow("MASK",mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
red = cv2.bitwise_and(img2,img2,mask=mask)
cv2.imshow("RED",red)
cv2.waitKey(0)
cv2.destroyAllWindows()
7、图像缩放
import cv2
import numpy as np
img=cv2.imread("pig.jpg")
rows,cols,_ = img.shape
#第一种缩放方式
size1 = (int(rows*0.9),int(cols*0.8))#宽变成0.9倍,长变成0.8倍
img_resize1 = cv2.resize(img,size1)
#第二种缩放方式
img_resize2 = cv2.resize(img,None,fx=2,fy=1.5)#宽变成两倍,长变成1.5倍
cv2.imshow("SRC",img)
cv2.imshow("RESIZE1",img_resize1)
cv2.imshow("RESIZE2",img_resize2)
cv2.waitKey(0)
cv2.destroyAllWindows()
8、图像插值
#示例,图像缩小操作
size1 = (int(rows*0.9),int(cols*0.8))#宽变成0.9倍,长变成0.8倍
img_resize1 = cv2.resize(img,size1,cv2.INTER_AREA)
cv2.imshow("RESIZE3",img_resize1)
cv2.waitKey(0)
cv2.destroyAllWindows()
9、图像翻转
img_flip1=cv2.flip(img,0)#x轴翻转
cv2.imshow("FLIP1",img_flip1)
cv2.waitKey(0)
cv2.destroyAllWindows()
10、平移
rows,cols,_ = img.shape
x = 100
y = 200
M = np.float32([[1,0,x],[0,1,y]])#转换矩阵
img_move=cv2.warpAffine(img,M,(cols,rows))#平移操作,注意(cols,rows)
cv2.imshow("MOVE",img_move)
cv2.waitKey(0)
cv2.destroyAllWindows()