参考:python-opencv2利用cv2.findContours()函数来查找检测物体的轮廓
试验用图:
1.图像二值化寻找边缘
#coding=UTF-8
import cv2 as cv
import numpy as np
def contours_demo(image):
dst = cv.GaussianBlur(image,(3,3),0)
gray = cv.cvtColor(dst,cv.COLOR_BGR2GRAY)
ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY_INV|cv.THRESH_OTSU)
#binary = cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,9,4)
cv.imshow("binary",binary)
cloneImage,contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
for i,contour in enumerate(contours):
cv.drawContours(image,contours,i,(0,255,0),2)
cv.imshow("detect contours",image)
scr = cv.imread("D:/academic/picture/opencv_data/pic3.png")
cv.imshow("input image",scr)
contours_demo(scr)
cv.waitKey(0)
cv.destroyAllWindows()
效果:
tips:
1.如果二值化之后的图像的底色是白色,那么最后的绘图会把整张图片框进去,如图所示(第三章图片的边框是绿色的):
2.
cloneImage,contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
这行代码因opencv版本而异,opencv2.x和4.x只需要写成
contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
而opencv3.x要写成第一行那种。
2.canny边缘检测寻找边缘
#coding=UTF-8
import cv2 as cv
import numpy as np
def edge_demo(image):
blurred = cv.GaussianBlur(image,(3,3),0)
gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)
grad_x = cv.Sobel(gray,cv.CV_16SC1,1,0)
grad_y = cv.Sobel(gray,cv.CV_16SC1,0,1)
#edge_output = cv.Canny(image,50,150)
# canny的高低阈值比例一般为1:2或1:3
edge_output = cv.Canny(grad_x,grad_y,50,150)
return edge_output
def contours_demo(image):
binary = edge_demo(image)
cv.imshow("binary",binary)
cloneImage,contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
for i,contour in enumerate(contours):
cv.drawContours(image,contours,i,(0,255,0),2)
cv.imshow("detect contours",image)
scr = cv.imread("D:/academic/picture/opencv_data/pic3.png")
cv.imshow("input image",scr)
contours_demo(scr)
cv.waitKey(0)
cv.destroyAllWindows()
效果: