import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread("images/1.jpg")
#img2 = cv2.imread("images/3.jpg")
#b,g,r = cv2.split(img2)
#image_rgb = cv2.merge((r,g,b))
#plt.imshow(image_rgb)
b, g ,r = cv2.split(img)
img_1 = cv2.merge((r,g,b))
plt.imshow(img_1)
# height, width, channel
height, width, channel = img.shape
print(height, width, channel)
# cv2.resize() 放大
resized_img = cv2.resize(img, (width*2, height*2), interpolation=cv2.INTER_LINEAR)
plt.imshow(resized_img)
# cv2.resize() 缩小
small_img = cv2.resize(img, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR)
plt.imshow(small_img)
# 1 平移
height, width = img.shape[:2]
M1 = np.float32([[1,0,100],[0,1,50]])# 平移矩阵, 100 图像向右移动100个像素,向下移动50个像素
move_img = cv2.warpAffine(img, M1,(width, height))
plt.imshow(move_img)
M2 = np.float32([[1,0,-100],[0,1,-50]])# 平移矩阵, 100 图像向左移动100个像素,向上移动50个像素
move_img2 = cv2.warpAffine(img, M2,(width, height))
plt.imshow(move_img2)
height, width = img.shape[:2]
center = (width // 2.0, height // 2.0)#旋转的中心
M3 = cv2.getRotationMatrix2D(center, 180, 1)# 1 表示旋转过程中没有缩放
rotation_img = cv2.warpAffine(img, M3, (width, height))
plt.imshow(rotation_img)
# cv2.getAffineTransform(p1, p2)
p1 = np.float32([[120,35],[215,45],[135,120]])
p2 = np.float32([[135,45],[300,110],[130,230]])
M4 = cv2.getAffineTransform(p1, p2)# 计算一个变换矩阵
trans_img = cv2.warpAffine(img, M4, (width, height))
plt.imshow(trans_img)
crop_img = img[100:400, 100:400]
plt.imshow(crop_img)
通过画布画一个长方形
# 长方形
rectangle = np.zeros((300,300), dtype='uint8')
rect_img = cv2.rectangle(rectangle,(25, 25), (275,275), 255, -1)
plt.imshow(rect_img)
再画一个圆
rectangle = np.zeros((300,300),dtype="uint8")
circle_img = cv2.circle(rectangle,(150,150),150,255, -1 )
plt.imshow(circle_img)
# 与运算:cv2.bitwise_and(), 00:0, 01:0, 10:0, 11:1
and_img = cv2.bitwise_and(rect_img, circle_img)
plt.imshow(and_img)
# OR 或运算, 01:1, 10:1, 00:0, 11:1
or_img = cv2.bitwise_or(rect_img, circle_img)
plt.imshow(or_img)```
## 6.3XOR (异或运算)
```python
#XOR 异或运算, 01:1,10:1, 00:0, 11:0
xor_img = cv2.bitwise_xor(rect_img, circle_img)
plt.imshow(xor_img)
(B, G, R) = cv2.split(img) #分离
plt.imshow(B)
plt.imshow(G)
plt.imshow(R)
# 2 融合
zeros = np.zeros(img.shape[:2],dtype="uint8")
plt.imshow(cv2.merge([zeros, zeros, R]))
plt.imshow(cv2.merge([B, zeros,zeros]))
plt.imshow(cv2.merge([zeros, G,zeros]))
# 灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.imshow(gray)
#HSV(色度、饱和度、纯度)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
plt.imshow(hsv)
# lab
lab =cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
plt.imshow(lab)