简体   繁体   中英

How to merge bounding boxes to detect group of spots?

I have a code that detectd sunspots but I want to count the number of sunspot groupd instead of the individual spots like the current output I have here

1

import os
import cv2 # opencv library
import numpy as np
import matplotlib.pyplot as plt

"""Make the pwd implementation"""
cwd = os.getcwd()
file = "/sunspot1.jpg"
path = cwd + file
image = cv2.imread(path,0)

image_1 = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
#plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
#plt.show()

#plot the image in graycolor
#gray = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
#plt.imshow(gray)
#plt.show()


# perform image thresholding
ret, thresh = cv2.threshold(image, 90, 255, cv2.THRESH_BINARY)
#plt.imshow(thresh, cmap = 'gray')
#plt.show()

#circle = cv2.circle(thresh, (249,249),(238),(0, 255, 0),1)
# plt.imshow(circle)
# plt.show()

# find taches contours
contours, hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
valid_cntrs = []

for i,cntr in enumerate(contours):
    x,y,w,h = cv2.boundingRect(cntr)
    #print("x = ",x,"y = ",y,"w = ",w,"h = ",h)
    if ((x-249)**2 + (y-249)**2)<= 238**2:
        valid_cntrs.append(cntr)
"""implement image size detection for the contour LINE 36"""
        
#count the taches number
taches= len(valid_cntrs);
#sunspot= 1*(10*groups+taches);

# count the number of dicovered sunspots
print("The number of taches is: ",taches)

if taches == 0:
    plt.imshow(image_1)
    plt.show()

else:

    contour_sizes = [(cv2.contourArea(contour), contour) for contour in valid_cntrs]

    for i in range(len(valid_cntrs)):
        x,y,w,h = cv2.boundingRect(contour_sizes[i][1])
        prevtaches = cv2.rectangle(image_1,(x,y),(x+w,y+h),(0,255,0),1)
plt.imshow(prevtaches)
plt.show()

Here is my code. How do I get my output to group the sunspots and look like instead this instead

2

Thanks.

What you can do is after thresholding (and before detecting the individual contours), you can perform morphological operations like dilation , to make the white area more broader, such that the nearby ones get connected and make one big contour. To do that, you can adjust you kernel size to fit your needs in the best way and can also play with the iterations argument.

You can refer this

After that, you can draw your contours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM