opencv 我怎么能计算出列中矩形的个数?

kgsdhlau  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(169)

我有一张这张照片。

把字母做成长方形。

img = cv2.imread('/content/drive/MyDrive/project/t2.jpg')
image = cv2.resize(img,None,None,0.4,0.4)
#cv2_imshow(image)

gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,190,255,cv2.THRESH_BINARY_INV)
kernel = np.ones((1,1), np.uint8)
img_dilation = cv2.dilate(thresh, kernel, iterations=1)
ctrs,_= cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
for i, ctr in enumerate(sorted_ctrs):
    x, y, w, h = cv2.boundingRect(ctr)
    roi = image[y:y+h, x:x+w]
    cv2.rectangle(image,(x,y),( x + w, y + h ),(36,255,12),2)
    if w >2  and h > 2:
      #os.chdir('{}'.format(folder_out))
      roi = cv2.resize(roi,(224,224))
      #cv2.imwrite('letter{}.jpg'.format(i), roi)
cv2_imshow(image)

这就是结果。

我想计算列中矩形的个数

我想要一个代码,可以计算列中矩形的数量。你能帮我解决这个问题吗?TT
也许你有简单的解决方案!!

rekjcdws

rekjcdws1#

绝对不是最佳的(三个循环),但这是有效的。
如果你有很多盒子,它应该被优化。
它基本上检查每一个项目,并将它们与已经记录的盒子进行比较。
如果当前框与组中的一个框有交集,则将其添加到该组。

import cv2 as cv
import numpy as np

img = cv.imread('./input.jpg')
image = cv.resize(img, None, None, 0.4, 0.4)

gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
_, thresh = cv.threshold(gray, 190, 255, cv.THRESH_BINARY_INV)
kernel = np.ones((1, 1), np.uint8)
img_dilation = cv.dilate(thresh, kernel, iterations=1)
ctrs, _ = cv.findContours(img_dilation.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv.boundingRect(ctr)[0])
bounding_rectangles = []

for i, _ctr in enumerate(sorted_ctrs):
    x, y, w, h = cv.boundingRect(_ctr)
    bounding_rectangles.append([x, y, w, h])
    _roi = image[y:y + h, x:x + w]
    cv.rectangle(image, (x, y), (x + w, y + h), (36, 255, 12), 2)
    
    if w > 2 and h > 2:
        roi = cv.resize(_roi, (224, 224))
        
cv.imshow("Output", image)
cv.waitKey(0)

groups = [[bounding_rectangles[0]]]
added_index = [0]

for i, rect_item in enumerate(bounding_rectangles[1:]):
    group_found = False
    
    for j, group_items in enumerate(groups):
        
        for k, group_item in enumerate(group_items):
            if (group_item[0] <= rect_item[0] <= group_item[0] + group_item[2]) and i + 1 not in added_index:
                added_index.append(i + 1)
                groups[j].append(rect_item)
                group_found = True
                break
                
        if group_found is True:
            break
                
    if group_found is False:
        added_index.append(i + 1)
        groups.append([rect_item])

print(f"Groups found: {len(groups)}")

for i, item in enumerate(groups):
    print(f"Group {i + 1}: Box quantity = {len(item)}")

相关问题