0
$\begingroup$

I'm working on a Python algorithm to detect individual cells of a grid passed by an image. Currently, I'm facing an issue where the values inside each cell are being selected as contours along with the cells themselves.

As you can see: enter image description here

Here's part of my current code:

# Read the image
image = cv2.imread(image_path)

# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to remove noise for simplifying grid line identification
blur = cv2.GaussianBlur(gray, (5,5), 0)

# Apply adaptive threshold to the image (to handle variations in brightness and contrast)
thresh = cv2.adaptiveThreshold(blur, 255, 1, 1, 11, 2)

# Find the largest contour, which represents the grid itself
max_area = 0
c = 0
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # here I tried both cv2.RETR_EXTERNAL and cv2.RETR_TREE but none of them seems to work

for i in contours:
    area = cv2.contourArea(i)
    if area > 1000:
        if area > max_area:
            max_area = area
            best_cnt = i
            image = cv2.drawContours(image, contours, c, (0, 255, 0), 3)
    c += 1

# Create a mask to search only within these boundaries
mask = np.zeros((gray.shape), np.uint8)
cv2.drawContours(mask, [best_cnt], 0, 255, -1)
cv2.drawContours(mask, [best_cnt], 0, 0, 2)


# Cut away the identified mask from the image
out = np.zeros_like(gray)
out[mask == 255] = gray[mask == 255]


# Apply blur and adaptive threshold to this new image
blur = cv2.GaussianBlur(out, (5,5), 0)
thresh = cv2.adaptiveThreshold(blur, 255, 1, 1, 11, 2)


# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

c = 0
for i in contours:
    area = cv2.contourArea(i)
    if area > 1000/2:
        cv2.drawContours(image, contours, c, (0, 255, 0), 3)
    c += 1

plt.imshow(image, cmap='gray')
plt.title('Immagine finale') # the result above
plt.axis('off')
plt.show()

Does anyone have suggestions on how I can improve the accuracy in detecting the boundaries of individual grid cells?

Thanks in advance.

$\endgroup$

1 Answer 1

0
$\begingroup$

Solved by just changing 1000 to a higher value (in my case 3000).

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .