赞
踩
- import cv2
- import numpy as np
-
- # Reading the image
- img = cv2.imread('test.jpg')
-
- # Showing the output
-
- cv2.imshow("Image", img)
- cv2.waitKey(0)
- cv2.destroyAllWindows()
- # convert to hsv colorspace
- hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
-
- # lower bound and upper bound for Green color
- lower_bound = np.array([25, 52, 72])
- upper_bound = np.array([100, 255, 255])
-
- # find the colors within the boundaries
- mask = cv2.inRange(hsv, lower_bound, upper_bound)
np.ones((7,7),np.uint8) 创建一个 5×5 8 位整数矩阵。
cv2.MORPH_CLOSE 从白色区域中去除不必要的黑噪声。
cv2.MORPH_OPEN 从遮罩的黑色区域去除白噪声。
- #define kernel size
- kernel = np.ones((7,7),np.uint8)
-
- # Remove unnecessary noise from mask
-
- mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
- mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
- # Segment only the detected region
- segmented_img = cv2.bitwise_and(img, img, mask=mask)
- # Find contours from the mask
- contours, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
-
- output = cv2.drawContours(segmented_img, contours, -1, (0, 0, 255), 3)
-
- # Showing the output
- imgs = np.hstack([img, output])
- cv2.imshow("Image", imgs)
找到区域面积大于300的,加入到color_bounding_rect链表里
- # For greencolor
- mask = cv2.dilate(mask, kernel)
-
- # Creating contour to track red color
- contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
- print('contours', contours)
- # print('hierarchy', hierarchy)
- color_bounding_rect = list()
- min_area = 300
-
- for pic, contour in enumerate(contours):
-
- area = cv2.contourArea(contour)
- if (area > min_area):
- color_bounding_rect.append(cv2.boundingRect(contour))
- for x, y, w, h in color_bounding_rect:
- print('x, y, w, h', x, y, w, h)
- img = cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
-
- cv2.putText(img, "green", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255))
-
-
- cv2.imshow("Image", img)
效果如下:
和Dilate函数差不多,不一样的地方是用B做卷机后取最小值
效果如下:
输入:
contour:带有轮廓信息的图像;
cv2.RETR_TREE:提取轮廓后,输出轮廓信息的组织形式,除了cv2.RETR_TREE还有以下几种选项:
cv2.CHAIN_APPROX_SIMPLE:指定轮廓的近似办法,有以下选项:
输出:
python3里返回三个值:image,contours,hierarchy
image:可能是跟输入contour类似的一张二值图;
contours:list结构,列表中每个元素代表一个边沿信息。每个元素是(x,1,2)的三维向量,x表示该条边沿里共有多少个像素点,第三维的那个“2”表示每个点的横、纵坐标;
注意:如果输入选择cv2.CHAIN_APPROX_SIMPLE,则contours中一个list元素所包含的x点之间应该用直线连接起来,这个可以用cv2.drawContours()函数观察一下效果。
hierarchy:返回类型是(x,4)的二维ndarray。x和contours里的x是一样的意思。如果输入选择cv2.RETR_TREE,则以树形结构组织输出,hierarchy的四列分别对应下一个轮廓编号、上一个轮廓编号、父轮廓编号、子轮廓编号,该值为负数表示没有对应项。
参考资料
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。