打开CV错误:在自动批注尝试期间,正在围绕单个对象创建多个边界框

2024-04-24 07:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用opencv为我的训练和测试图像自动创建边界框。 我收到的错误是:围绕一个对象创建了多个边界框。enter image description here

其中原始图像(注释前)如下所示: enter image description here

下面是我使用的代码:

import cv2
import numpy as np
from os import listdir
from os.path import isfile, join
import numpy
import config


mypath = config.mypath

xx = mypath.split('/')
folder_path = xx[-2]
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
images = numpy.empty(len(onlyfiles), dtype=object)

for n in range(0, len(onlyfiles)):
    #images[n] = cv2.imread( join(mypath,onlyfiles[n]) )
    images[n] = cv2.imread( join(mypath,onlyfiles[n]),1 )
    xy = onlyfiles[n].split('.')
    print(xy[0])
    #img = cv2.imread('345.jpg')
    img = images[n]
    #print(images[n])
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # binarize the image
    ret, bw = cv2.threshold(gray, 128, 255,
    cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

    # find connected components
    connectivity = 4
    nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(bw, connectivity, cv2.CV_32S)
    sizes = stats[1:, -1]; nb_components = nb_components - 1
    min_size = 25000 #threshhold value for objects in scene
    img2 = np.zeros((img.shape), np.uint8)
    for i in range(0, nb_components+1):
        #print(i)
        # use if sizes[i] >= min_size: to identify your objects
        color = np.random.randint(255,size=3)
        x = (stats[i][2])

        if  (650>x>130):

            #cv2.rectangle(img, (217,203),(349,335), (0,255,0), 2)
            x1 = stats[i][0]
            x2 = stats[i][1]
            x3 = stats[i][0]+stats[i][2]
            x4 = stats[i][1]+stats[i][3]


            cv2.rectangle(img, (x1,x2),(x3,x4), (0,255,0), 2)

            print((x1,x2),(x3,x4))
            #print (stats[i][2])

    # draw the bounding rectangele around each object

        img2[output == i + 1] = color

    folder_xml = folder_path
    filename_xml = (onlyfiles[n])
    path_xml1 = (join(mypath,onlyfiles[n]))
    path_xml = path_xml1.replace("/","\\")
    name_xml = folder_path

    xmin_xml = stats[i][0]
    ymin_xml = stats[i][1]
    xmax_xml = stats[i][0]+stats[i][2]
    ymax_xml = stats[i][1]+stats[i][3]



    xml_name = xy[0]

    #print((onlyfiles[n]))



    #plt.imshow(img)
    cv2.imshow('frame',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    #!/usr/bin/python
    #-*- coding: utf-8 -*-
    #text.encode('UTF-8')

请帮助我了解可能的错误? 提前谢谢!你知道吗


Tags: pathimportimgforstatsnpcomponentsxml