2020-06-17-image-process-canny

Record

Posted by Jocelyn on June 17, 2020

2020-06-17-recording.

形态学

# -*- coding: UTF-8 -*-
#形态学-腐蚀操作
#对于不是二值的图片也是可以进行的
import cv2
import numpy as np
img = cv2.imread('/Users/syy/learn/repositories/blogPost/JocelynHub.github.io/img/post-sample-image.jpg')
img = img[300:500,300:500]
# cv2.imshow('img',img)
# cv2.waitKey(0)
# cv2.destroyWindow('img')

kernel = np.ones((3,3),np.uint8)
erosion = cv2.erode(img,kernel,iterations=3)
# cv2.imshow('erode',erosion)
# cv2.waitKey(0)
# cv2.destroyWindow('erode')

#膨胀操作
dige_dilate = cv2.dilate(erosion,kernel,iterations=3)
# cv2.imshow('dilate',dige_dilate)
# cv2.waitKey(0)
# resH = np.hstack((img,erosion,dige_dilate))
# cv2.imshow('pack',resH)
# cv2.waitKey(0)
#腐蚀之后进行膨胀,并不一定能够回到原图的样子

#开运算和闭运算,这里的开运算和闭运算只是将腐蚀和膨胀连成一个整体
opening = cv2.morphologyEx(img,cv2.MORPH_OPEN,kernel)
#表示的是先进行腐蚀,再进行膨胀

closing = cv2.morphologyEx(img,cv2.MORPH_CLOSE,kernel)
#表示的是先进行膨胀,再进行腐蚀

#梯度运算
#利用膨胀-腐蚀
dilate = cv2.dilate(img,kernel,iterations=2)
erision = cv2.erode(img,kernel,iterations=2)

gradient = cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
# cv2.imshow('gradient',gradient)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#出来的图好酷炫

#tophat blackhat
#tophat是原始输入-开运算结果--原始输入 减去 先腐蚀再膨胀,得到尖刺
#blackhat是闭运算-原始输入--先膨胀再腐蚀 减去原始输入,得到轮廓
tophat = cv2.morphologyEx(img,cv2.MORPH_TOPHAT,kernel)
blackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT,kernel)
resH=np.hstack((tophat,blackhat))
# cv2.imshow('hat',resH)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

梯度和边缘检测

#图像梯度,有边缘的地方才有梯度
def cv_show(image,name):
    cv2.imshow(name,image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
#dst = cv2.Sobel(src,ddepth,dx,dy,ksize)
#ddepth:图像的深度,通常为-1
#dx dy分别表示在水平方向和竖直方向
#ksize是计算Sobel算子的大小

#opencv的显示范围是0~255,所以会对负数进行截断
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
#cv2.CV_64F是为了扩大范围到负数
#转换为绝对值
sobelx = cv2.convertScaleAbs(sobelx)

sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
#分别计算x y然后再求和
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
#如果同时计算,得到的态度效果比较模糊,
sobels = cv2.Sobel(img,cv2.CV_64F,1,1,ksize=3)
resH=np.hstack((sobelxy,sobels))
# 这里要注意,这里还是跟matlab一样,会存在归一化问题,下面两幅图的会有差异
# cv_show(resH,'compare')
# cv_show(sobelxy,'compare')
#图像梯度 scharr和laplacian算子
scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(scharrx,0.5,scharry,0.5,0)

#laplacian写法更简单
laplacian = cv2.Laplacian(img,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
# canny边缘检测
v1 = cv2.Canny(img,80,150)
#80 150位两个阈值
#如果都比较小,边缘信息更多,考虑到更多的噪声点