How to improve contour detection of holes in white wall

72 Views Asked by At

enter image description here I want to identify the black spots in this image.

While Canny edge detection captures most of the features, enter image description here

using contours, _ = cv2.findContours(thresholded, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) only detects a few isolated points. Is there a way to improve this? enter image description here

import cv2
import numpy as np

image1 = cv2.imread(r"C:\Users\54-0461100-01\Desktop\img_process\Daphnia\WIN_20231103_09_47_45_Pro.jpg")

gray_image = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)

_, thresholded = cv2.threshold(gray_image, 100, 255, cv2.THRESH_BINARY)  
kernel = np.ones((5, 5), np.uint8)  

thresholded = cv2.dilate(thresholded, kernel, iterations=1)
cv2.imshow('thresholded1', thresholded)

thresholded = cv2.Canny(thresholded, 100, 200)
cv2.imshow('thresholded2', thresholded)
cv2.imwrite("thresholded2.jpg", thresholded)

contours, _ = cv2.findContours(thresholded, cv2.RETR_LIST  , cv2.CHAIN_APPROX_SIMPLE)#cv2.CHAIN_APPROX_SIMPLE

object_count = 0
img_with_boxes = image1.copy()

for contour in contours:
    area = cv2.contourArea(contour)
    if area < 15:  #
        x, y, w, h = cv2.boundingRect(contour)
        img_with_boxes = cv2.rectangle(img_with_boxes, (x, y), (x + w, y + h), (0, 0, 255), 2)
        object_count += 1

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img_with_boxes, f'Black Dots: {object_count}', (10, 30), font, 1, (0, 0, 255), 2, cv2.LINE_AA)

cv2.imwrite("detected_black_dots.jpg", img_with_boxes)
cv2.imshow('Black Dots Detected', img_with_boxes)
cv2.waitKey(0)
cv2.destroyAllWindows()
0

There are 0 best solutions below