此系列博客记录 网易云课堂 python + openCV图像处理课程的学习过程。
本篇博客将介绍 形态学操作、图像梯度 两大部分。
erosion.png
maoci.png
paopao.png
1、形态学操作
import cv2
import numpy as np
a = cv2.imread(r"C:\workspace\python\openCV\maoci.png",cv2.IMREAD_UNCHANGED)
kernel = np.ones((5,5),np.uint8)
erosion = cv2.erode(a,kernel,iterations=9) # 图像腐蚀
cv2.imwrite(r"C:\workspace\python\openCV\erosion.png",erosion)
dilation = cv2.dilate(erosion,kernel,iterations=9) #图像膨胀
cv2.imshow("a",a)
cv2.imshow("erosion",erosion)
cv2.imshow("dilation",dilation)
cv2.waitKey()
cv2.destroyAllWindows()
erode(src,kernel,iterations)
dilate(src,kernel,iterations)
其中,src 是目标图像,kernel 是卷积核,iterations 是迭代次数(缺省值为1)
效果图:
import cv2
import numpy as np
a = cv2.imread(r"C:\workspace\python\openCV\maoci.png",cv2.IMREAD_UNCHANGED)
kernel = np.ones((10,10),np.uint8)
b = cv2.morphologyEx(a,cv2.MORPH_OPEN,kernel) # 开运算
# b = cv2.morphologyEx(a,cv2.MORPH_CLOSE,kernel) # 闭运算
# b = cv2.morphologyEx(a,cv2.MORPH_GRADIENT,kernel) # 梯度运算
# b = cv2.morphologyEx(a,cv2.MORPH_TOPHAT,kernel) # 礼帽操作
# b = cv2.morphologyEx(a,cv2.MORPH_BLACKHAT,kernel) #黑帽操作
cv2.imshow("a",a)
cv2.imshow("b",b)
cv2.waitKey()
cv2.destroyAllWindows()
2、图像梯度
import cv2
import numpy as np
a = cv2.imread(r"C:\workspace\python\openCV\xiaoxin.png",cv2.IMREAD_UNCHANGED)
sobelx = cv2.Sobel(a,cv2.CV_64F,1,0) # x方向梯度
sobely = cv2.Sobel(a,cv2.CV_64F,0,1) # y方向梯度
sobelx = cv2.convertScaleAbs(sobelx) # x的绝对值
sobely = cv2.convertScaleAbs(sobely) # y的绝对值
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0) # x与y相加
cv2.imshow("original",a)
cv2.imshow("xy",sobelxy)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
a = cv2.imread(r"C:\workspace\python\openCV\xiaoxin.png",cv2.IMREAD_UNCHANGED)
scharrx = cv2.Scharr(a,cv2.CV_64F,1,0) # x方向梯度
scharry = cv2.Scharr(a,cv2.CV_64F,0,1) # y方向梯度
scharrx = cv2.convertScaleAbs(scharrx) # x的绝对值
scharry = cv2.convertScaleAbs(scharry) # y的绝对值
scharrxy = cv2.addWeighted(scharrx,0.5,scharry,0.5,0) # x与y相加
cv2.imshow("original",a)
cv2.imshow("xy",scharrxy)
cv2.waitKey()
cv2.destroyAllWindows()
效果图:
原理:
import cv2
import numpy as np
a = cv2.imread(r"C:\workspace\python\openCV\xiaoxin.png",cv2.IMREAD_UNCHANGED)
lapiacian = cv2.Laplacian(a,cv2.CV_64F)
lapiacian = cv2.convertScaleAbs(lapiacian) # 转回uint8
cv2.imshow("original",a)
cv2.imshow("lapiacian",lapiacian)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
import numpy as np
a = cv2.imread(r"C:\workspace\python\openCV\xiaoxin.png",cv2.IMREAD_UNCHANGED)
b = cv2.Canny(a,100,200) #细节更多的话,同时调低两个参数就行
cv2.imshow("original",a)
cv2.imshow("result",lapiacian)
cv2.waitKey()
cv2.destroyAllWindows()