|
| 1 | +# -*- coding:utf-8 -*- |
| 2 | +# By: Eastmount CSDN 2021-08-19 |
| 3 | +import cv2 |
| 4 | +import numpy as np |
| 5 | +import matplotlib.pyplot as plt |
| 6 | + |
| 7 | +#读取图片 |
| 8 | +src = cv2.imread("Lena.png") |
| 9 | + |
| 10 | +#获取图像宽和高 |
| 11 | +rows, cols = src.shape[:2] |
| 12 | + |
| 13 | +#BGR转换为RGB |
| 14 | +img = cv2.cvtColor(src, cv2.COLOR_BGR2RGB) |
| 15 | + |
| 16 | +#(1)OpenCV加法运算 |
| 17 | +m = np.ones(img.shape, dtype="uint8")*100 #图像各像素加100 |
| 18 | +result1 = cv2.add(img, m) |
| 19 | + |
| 20 | +#(2)OpenCV减法运算 |
| 21 | +m = np.ones(img.shape, dtype="uint8")*50 #图像各像素减50 |
| 22 | +result2 = cv2.subtract(img, m) |
| 23 | + |
| 24 | +#(3)画圆形 |
| 25 | +circle = np.zeros((rows, cols, 3), dtype="uint8") |
| 26 | +cv2.circle(circle, (int(rows/2.0), int(cols/2)), 100, (255,0,0), -1) |
| 27 | +print(circle.shape,img.size, circle.size) |
| 28 | + |
| 29 | +#(4)OpenCV图像与运算 |
| 30 | +result4 = cv2.bitwise_and(img, circle) |
| 31 | + |
| 32 | +#(5)OpenCV图像或运算 |
| 33 | +result5 = cv2.bitwise_or(img, circle) |
| 34 | + |
| 35 | +#(6)OpenCV图像异或运算 |
| 36 | +result6 = cv2.bitwise_xor(img, circle) |
| 37 | + |
| 38 | +#(7)OpenCV图像非运算 |
| 39 | +result7 = cv2.bitwise_not(img) |
| 40 | + |
| 41 | +#解决中文显示问题 |
| 42 | +plt.rcParams['font.sans-serif'] = ['KaiTi'] #指定默认字体 |
| 43 | +plt.rcParams['axes.unicode_minus'] = False #解决保存图像是负号 |
| 44 | + |
| 45 | +#显示九张图像 |
| 46 | +titles = ['原图', 'RGB', '加法', '减法', '圆形', '与运算', '或运算', '异或运算', '非运算'] |
| 47 | +images = [src, img, result1, result2, circle, result4, result5, result6, result7] |
| 48 | +for i in range(9): |
| 49 | + plt.subplot(3, 3, i+1), plt.imshow(images[i], 'gray') |
| 50 | + plt.title(titles[i]) |
| 51 | + plt.xticks([]),plt.yticks([]) |
| 52 | +plt.show() |
| 53 | + |
| 54 | + |
| 55 | + |
0 commit comments