opencv学习—亮点检测(python)
目录
为啥叫亮点检测,因为该方法是用来检测一张图像或者视频中的亮点区域,并进行统计,举个简单的例子,一张图像中有100个发光的灯泡,因为故障原因,其中若干个灯泡发生故障,那么该如何统计有效发光的灯泡数量呢?该方法就是用来解决类似问题的。
方法流程如下:
1、输入原图像
2、原图像灰度化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
3、平滑滤波
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
4、阈值分割
thresh = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)[1]
5、形态学运算移除斑点
- 膨胀腐蚀操作
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=4)
- 连接组件分析
labels = measure.label(thresh, neighbors=8, background=0)
mask = np.zeros(thresh.shape, dtype="uint8")
for label in np.unique(labels):
# if this is the background label, ignore it
if label == 0:
continue
labelMask = np.zeros(thresh.shape, dtype="uint8")
labelMask[labels == label] = 255
numPixels = cv2.countNonZero(labelMask)
if numPixels > 300:
mask = cv2.add(mask, labelMask)
cv2.imshow('mask',mask)
cv2.waitKey(0)
结果图:
6、标记斑点-轮廓检测-输出图像
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = contours.sort_contours(cnts)[0]
for (i, c) in enumerate(cnts):
(x, y, w, h) = cv2.boundingRect(c)
((cX, cY), radius) = cv2.minEnclosingCircle(c)
cv2.circle(image, (int(cX), int(cY)), int(radius),
(0, 0, 255), 3)
cv2.putText(image, "{}".format(i + 1), (x, y - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)
从结果图像来看检测出图像中亮点有5个。
完整Code
from imutils import contours
from skimage import measure
import numpy as np
import cv2
image = cv2.imread('E:\\car\\6.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (11, 11), 0)
cv2.imshow('blurred',blurred)
cv2.waitKey(0)
thresh = cv2.threshold(blurred, 200, 255, cv2.THRESH_BINARY)[1]
cv2.imshow('thresh',thresh)
cv2.waitKey(0)
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=4)
labels = measure.label(thresh, neighbors=8, background=0)
mask = np.zeros(thresh.shape, dtype="uint8")
for label in np.unique(labels):
if label == 0:
continue
labelMask = np.zeros(thresh.shape, dtype="uint8")
labelMask[labels == label] = 255
numPixels = cv2.countNonZero(labelMask)
if numPixels > 300:
mask = cv2.add(mask, labelMask)
cv2.imshow('mask',mask)
cv2.waitKey(0)
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = contours.sort_contours(cnts)[0]
for (i, c) in enumerate(cnts):
(x, y, w, h) = cv2.boundingRect(c)
((cX, cY), radius) = cv2.minEnclosingCircle(c)
cv2.circle(image, (int(cX), int(cY)), int(radius),
(0, 0, 255), 3)
cv2.putText(image, "{}".format(i + 1), (x, y - 2),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.imshow("Image", image)
cv2.waitKey(0)