G
G
gareaf2021-09-13 15:08:40
Python
gareaf, 2021-09-13 15:08:40

How to separate squares that overlap?

The essence of the problem: you need to count the number of squares.
There is a picture on which there is noise, I removed them, but I don’t know how to separate the squares that intersect or you can count the squares without separation.
I will be grateful for any help.

here is a picture with noise
https://imgur.com/a/gI8Zjbl here is a code

without noise
613f3fdc63d94352373875.png

import cv2
import matplotlib.pyplot as plt 


image = cv2.imread("1.bmp")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

_, binary = cv2.threshold(gray, 3, 255, cv2.THRESH_BINARY)
plt.imshow(binary, cmap="gray")
plt.show()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-09-13
@gareaf

For a particular case, if your squares are approximately the same and mostly touching:
- we get the contours of the elements using cv2.findContours in the contours
list - we find the area of ​​the most frequently occurring element using collections.Counter.most_common using the found contours - we will find the area of ​​one square - in fact the number of pixels in one square

occurence_count = Counter(map(lambda x:cv2.contourArea(x), contours))
most_common_area = round(occurence_count.most_common(1)[0][0])

- find the total number of black pixels black_pixels = np.sum(binary == 0)
- divide the total number of black pixels by the number of pixels in one square, round up - get the total number of squares in the picture
I got about 1035

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question