图像色彩操作
二值化与反二值化
import cv2 as cv
img = cv.imread("../data/lena.jpg", 0)
cv.imshow("img", img)
t, rst = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
cv.imshow("rst", rst)
t, rst2 = cv.threshold(img, 127, 255, cv.THRESH_BINARY_INV)
cv.imshow("rst2", rst2)
cv.waitKey()
cv.destroyAllWindows()
图像形态操作
图像相加
import cv2
a=cv2.imread('../img_data/lena.jpg',0)
b=cv2.imread('../img_data/lily_square.png',0)
dst1=cv2.add(a,b)
dst2=cv2.addWeighted(a,0.6,b,0.4,0)
cv2.imshow('a',a)
cv2.imshow('b',b)
cv2.imshow('dst1',dst1)
cv2.imshow('dst2',dst2)
cv2.waitKey()
cv2.destroyAllWindows()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bc4656fd7b794033e55ecb1ace90ab1f.png)
图像裁剪
import numpy as np
import cv2
def random_crop(im, w, h):
start_x = np.random.randint(0, im.shape[1])
start_y = np.random.randint(0, im.shape[0])
new_img = im[start_y:start_y + h, start_x:start_x + w]
return new_img
def center_crop(im, w, h):
start_x = int(im.shape[1] / 2) - int(w / 2)
start_y = int(im.shape[0] / 2) - int(h / 2)
new_img = im[start_y:start_y + h, start_x:start_x + w]
return new_img
if __name__ == '__main__':
im = cv2.imread('../img_data/banana_1.png', 1)
new_img = random_crop(im, 200, 200)
cv2.imshow('rand_crop', new_img)
new_img2 = random_crop(im, 200, 200)
cv2.imshow('center_crop', new_img2)
cv2.waitKey()
cv2.destroyAllWindows()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/271ba708fee25c83cb0da8b20a4760e0.png)