#引入opencv模块
import cv2 as cv
#引入numpy模块
import numpy as np
#引入sys模块
import sys
#countours
def countours_detection(img):
#(1)加滤波,能消除噪声
dst = cv.GaussianBlur(img,(3,3),0)
gray = cv.cvtColor(dst,cv.COLOR_BGR2GRAY)
ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
cv.imshow("binary image",binary)
#contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE) #查找所有
#只找最外面的,重要!!!
contours,heriachy = cv.findContours(binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
#cv.drawContours(img,contours,-1,(0,0,255),2) #画出所有
for i,countour in enumerate(contours):
cv.drawContours(img,contours,i,(0,0,255),2)
#-1参数会填充掉轮廓,注意!
#cv.drawContours(img,contours,i,(0,0,255),-1)
print(i)
return img
#edge_detection
def edge_detection(img):
blurred = cv.GaussianBlur(img,(3,3),0)
gray = cv.cvtColor(blurred,cv.COLOR_BGR2GRAY)
edge_output = cv.Canny(gray,50,150)
cv.namedWindow("canny_edge",cv.WINDOW_NORMAL)
cv.imshow("canny_edge",edge_output)
return edge_output
#countours2
def countours2_detection(img):
binary = edge_detection(img)
#contours,heriachy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE) #查找所有
#只找最外面的,重要!!!
contours,heriachy = cv.findContours(binary,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
#cv.drawContours(img,contours,-1,(0,0,255),2) #画出所有
for i,countour in enumerate(contours):
cv.drawContours(img,contours,i,(0,0,255),2)
#-1参数会填充掉轮廓,注意!
#cv.drawContours(img,contours,i,(0,0,255),-1)
print(i)
return img
def img_test():
#img = cv.imread('E:/chenopencvblogimg/lena.jpg')
#img = cv.imread('E:/chenopencvblogimg/star.png')
img = cv.imread('E:/chenopencvblogimg/circle.png')
#判断是否读取成功
if img is None:
print("Could not read the image,may be path error")
return
cv.namedWindow("origin Pic",cv.WINDOW_NORMAL)
cv.imshow("origin Pic",img)
#countours_detection(img)
img_show = countours_detection(img)
cv.namedWindow("countours_detection",cv.WINDOW_NORMAL)
cv.imshow("countours_detection",img_show)
img_show = countours2_detection(img)
cv.namedWindow("countours2_detection",cv.WINDOW_NORMAL)
cv.imshow("countours2_detection",img_show)
#让显示等待键盘输入维持在那里,否则程序跑完就闪退啦!
cv.waitKey(0)
#销毁窗口
cv.destroyAllWindows()
if __name__ == '__main__':
sys.exit(img_test() or 0)