K
K
kr_ilya2021-06-28 11:22:31
Python
kr_ilya, 2021-06-28 11:22:31

Determining the number of squares with an intersection?

You need to find the number of squares with intersection in the picture.
Now there is this code:

import cv2
import numpy as np

img = cv2.imread('./task1.bmp', cv2.IMREAD_UNCHANGED)

#convert img to grey
img_grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#set a thresh
thresh = 100
#get threshold image
ret,thresh_img = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)
#find contours
contours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# print(len(contours))
#create an empty image for contours
img_contours = np.zeros(img.shape)
# draw the contours on the empty image
cv2.drawContours(img_contours, contours, -1, (0,255,0), 3)
#save image
cv2.imwrite('./res.bmp',img_contours)

Original image:
60d9851782dd9066521901.png

Result after processing
60d9854630c1b340310064.png

As you can see, the squares in the pictures intersect and the program finds their common contours. It is necessary that the program find exactly the contours of the squares and count them.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-06-28
@Vindicar

Do you know the size of the square? Use a sliding window.
Cut out in turn all fragments of the image of this size, if it is completely black, then we fix the square in this position.
There may be false positives if two overlapping squares are perfectly aligned on the same vertical/horizontal. Here you need to search for all triggers in this area, and select the extreme left / right or bottom / top.

U
U235U235, 2021-06-29
@U235U235

Everything is done literally in three teams.
1. Closing with cv2.morphologyEx, the core is square, 2 times smaller than squares. Single squares are removed.
2. inversion. cv2.bitwise_not
3. cv2.connectedComponents count remaining connected squares.
If you need to select individual squares in the union, then use cv2 after step 1. matchTemplate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question