我正在尝试识别柠檬上的黑点,我尝试了几次。我很难将黑色阴影与柠檬上的实际黑色污渍区分开。
我尝试使用InRange
并将图像转换为HSV失败,说实话,我很迷失了,不胜感激一些识别黑斑的新想法。
这是我的代码:
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread("./data/lemon1big.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
plt.imshow(thresh)
结果:
这些是我要检测的污渍-我检测到12种污渍:
答案 0 :(得分:1)
我建议使用自适应阈值而不是otsu,因为黑色背景会干扰otsu的阈值计算,然后您可以使用连接的分量分析并按大小过滤来获得黑点,此处代码如下:
import cv2
import matplotlib.pyplot as plt
def plotImg(img):
if len(img.shape) == 2:
plt.imshow(img, cmap='gray')
plt.show()
else:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.show()
img = cv2.imread('lemon.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
binary_img = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 131, 15)
plotImg(binary_img)
_, _, boxes, _ = cv2.connectedComponentsWithStats(binary_img)
# first box is the background
boxes = boxes[1:]
filtered_boxes = []
for x,y,w,h,pixels in boxes:
if pixels < 10000 and h < 200 and w < 200 and h > 10 and w > 10:
filtered_boxes.append((x,y,w,h))
for x,y,w,h in filtered_boxes:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255),2)
plotImg(img)