原图
下面的
show_img
方法是封装了
cv2.imshow()
和
cv2.waitKey()
,方便我自己使用,不用每次输入窗口名称,不用每次都waitKey。
形态学操作
腐蚀,膨胀,开,闭,就不掩饰了。
源码
def main():
"""
测试形态学操作
:return:
"""
img_path = "./pictures/icons/screenshot.jpg"
img = cv2.imread(img_path)
show_img(img)
# 进行形态学梯度运算
k = np.ones((2,2), np.int) # 核
r = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, k) # 形态学梯度运算
show_img(r)
# 礼帽运算
k = np.ones((2, 2), np.int) # 核
r = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, k) # 礼帽运算
show_img(r)
# 黑帽运算
k = np.ones((2, 2), np.int) # 核
r = cv2.morphologyEx(img, cv2.MORPH_BLACKHAT, k) # 黑帽运算
show_img(r)
形态学梯度运算结果
礼帽运算结果
黑帽运算结果
Sobel算子,Scharr算子和Laplacian算子
源码
def main():
"""
测试图像梯度
:return:
"""
img_path = "./pictures/icons/screenshot.jpg"
img = cv2.imread(img_path)
show_img(img)
sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0)
sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1)
sobel_x = cv2.convertScaleAbs(sobel_x)
sobel_y = cv2.convertScaleAbs(sobel_y)
sobel_xy = cv2.addWeighted(sobel_x, 0.5, sobel_y, 0.5, 0)
show_img(sobel_xy)
scharr_x = cv2.Scharr(img, cv2.CV_64F, 1, 0)
scharr_y = cv2.Scharr(img, cv2.CV_64F, 0, 1)
scharr_x = cv2.convertScaleAbs(scharr_x)
scharr_y = cv2.convertScaleAbs(scharr_y)
scharr_xy = cv2.addWeighted(scharr_x, 0.5, scharr_y, 0.5, 0)
show_img(scharr_xy)
laplacian = cv2.Laplacian(img, cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
show_img(laplacian)
Sobel算子
Scharr算子
Laplacian算子
Canny 边缘检测
源码
def main():
"""
Canny 边缘检测
:return:
"""
img_path = "./pictures/icons/screenshot.jpg"
img = cv2.imread(img_path)
r1 = cv2.Canny(img, 128, 200)
r2 = cv2.Canny(img, 32, 128)
show_img(r1)
show_img(r2)
两种不同的核的结果
findContours图像轮廓
源码
def main5():
"""
查找图像轮廓
:return:
"""
img_path = "./pictures/icons/screenshot.jpg"
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
o = cv2.drawContours(img, contours, -1, (0,255,255), 1)
show_img(o)
结果