直接上代码:
import cv2 import numpy as np def isPointInBlackContours(point, frame, maskBlackImgPath, maskImgPath): ######步骤1:提取出黑色区域置为白亮,其他区域置为黑色背景化: # 把 BGR 转为 HSV hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # HSV中黑色范围 lower_blue = np.array([0, 0, 0]) upper_blue = np.array([0, 0, 0]) # 获得黑色区域的mask mask = cv2.inRange(hsv, lower_blue, upper_blue) # 和原始图片进行and操作,获得黑色区域。黑色区域置为白亮,其他区域置为黑色背景化。 res = cv2.bitwise_and(frame, frame, mask=mask) cv2.imwrite(maskBlackImgPath, mask) ######步骤2:轮廓检测并且绘制保存在本地 # 读入图像、灰度、二值化 img_src = cv2.imread(maskBlackImgPath) img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY) val, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY) # 查找轮廓 contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) print('len(contours):', len(contours)) # 绘制轮廓 validContoursList = [] for ind in range(len(contours)): # perimeter = cv2.arcLength(contours[ind], True) contourArea=cv2.contourArea(contours[ind], False) if (contourArea>500):#自定义阈值,抑制过小的误检轮廓或者黑颜色物体 print("contourArea:"+str(contourArea)) print("Valid Contour index:" + str(ind)) cv2.drawContours(img_src, contours, ind, (0, 0, 255), 3) validContoursList.append(contours[ind]) cv2.imwrite(maskImgPath, img_src) ####步骤3:判断一个点是否在轮廓内 # img = cv2.imread(maskImgPath) # img = cv2.circle(img, point, 2, (255, 0, 0), 2) # 蓝色 for indexJ in range(len(validContoursList)): dstJ = cv2.pointPolygonTest(validContoursList[indexJ], point, 1) print("dst"+str(indexJ)+':'+str(dstJ)) if(dstJ>=0): #距离>=0,说明在黑色轮廓以及内部 return True return False pt = (131, 104) frame = cv2.imread('d:/11.jpg') maskBlackImgPath1='d:/mask1.jpg' maskImgPath1='d:/validContours2.jpg' res1=isPointInBlackContours(pt,frame,maskBlackImgPath1,maskImgPath1) print('res:'+str(res1))
原图11.jpg :
结果图 mask1.jpg (原黑色块高亮显示):
结果图 validContours2.jpg (用红色框,自动标记出原黑色噪声块):
参考①:
OpenCV-Python教程:查找轮廓、绘制轮廓_python获取轮廓上两点之间的所有点_桔子code的博客-CSDN博客
参考②:
opencv 判断点在多边形内外_cv2.pointpolygontest_alex1801的博客-CSDN博客
参考③: