我正在尝试识别柠檬上的黑点,我已经尝试了几次。我无法区分黑色阴影和柠檬上的实际黑色污渍。
我尝试使用
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 个污渍:
我建议使用自适应阈值而不是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)
我能够检测到黑点,但无法检测到靠近边缘的斑点。谁能帮帮我吗?
这是我使用的代码:
def detect_black_spots(img):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #Chuyển đổi một hình ảnh từ không gian màu BGR (Blue, Green, Red) sang không gian màu xám (grayscale).
binary_img = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 101, 6.5)
_, _, boxes, _ = cv2.connectedComponentsWithStats(binary_img)
#plotImg(binary_img)
# Hộp đầu tiên là nền
boxes = boxes[1:]
filtered_boxes = []
for x,y,w,h,pixels in boxes:
if pixels < 10000 and h < 200 and w < 200 and h > 2 and w > 2:
filtered_boxes.append((x,y,w,h))
#cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255),2)
#plotImg(img)
if len(filtered_boxes) > 0:
return True
return False