1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import cv2 import numpy as np import matplotlib.pyplot as plt
def put(path): img = cv2.imread(path) b, g, r = cv2.split(img) img2 = cv2.merge([r, g, b])
grayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gaussianBlur = cv2.GaussianBlur(grayImage, (3, 3), 0)
ret, binary = cv2.threshold(grayImage, 127, 255, cv2.THRESH_BINARY)
x = cv2.Sobel(grayImage, cv2.CV_16S, 1, 0) y = cv2.Sobel(grayImage, cv2.CV_16S, 0, 1) absX = cv2.convertScaleAbs(x) absY = cv2.convertScaleAbs(y) Sobel = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
kernelx = np.array([[-1, 0], [0, 1]], dtype=int) kernely = np.array([[0, -1], [1, 0]], dtype=int) x = cv2.filter2D(grayImage, cv2.CV_16S, kernelx) y = cv2.filter2D(grayImage, cv2.CV_16S, kernely) absX = cv2.convertScaleAbs(x) absY = cv2.convertScaleAbs(y) Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
dst = cv2.Laplacian(grayImage, cv2.CV_16S, ksize=3) Laplacian = cv2.convertScaleAbs(dst)
gaussian = cv2.GaussianBlur(grayImage, (5, 5), 0)
Canny = cv2.Canny(gaussian, 50, 150)
kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int) kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int) x = cv2.filter2D(grayImage, cv2.CV_16S, kernelx) y = cv2.filter2D(grayImage, cv2.CV_16S, kernely) absX = cv2.convertScaleAbs(x) absY = cv2.convertScaleAbs(y) Prewitt = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
gaussian = cv2.GaussianBlur(grayImage, (3, 3), 0) dst = cv2.Laplacian(gaussian, cv2.CV_16S, ksize=3) LOG = cv2.convertScaleAbs(dst)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.subplot(241), plt.imshow(img2), plt.title('原始图像'), plt.axis('off') plt.subplot(242), plt.imshow(binary, plt.cm.gray), plt.title('二值图'), plt.axis('off') plt.subplot(243), plt.imshow(Sobel, plt.cm.gray), plt.title('Sobel算子'), plt.axis('off') plt.subplot(244), plt.imshow(Roberts, plt.cm.gray), plt.title('Roberts算子'), plt.axis('off') plt.subplot(245), plt.imshow(Laplacian, plt.cm.gray), plt.title('拉普拉斯算子'), plt.axis('off') plt.subplot(246), plt.imshow(Canny, plt.cm.gray), plt.title('Canny算子'), plt.axis('off') plt.subplot(247), plt.imshow(Prewitt, plt.cm.gray), plt.title('Prewitt算子'), plt.axis('off') plt.subplot(248), plt.imshow(LOG, plt.cm.gray), plt.title('高斯拉普拉斯算子'), plt.axis('off')
plt.show()
put(r'laohu.jpg')
|