首页 > 解决方案 > Open CV Error: Multiple bounding boxes are being created around one single object during automated annotation attempt

问题描述

I am trying to automate bounding box creation process for my train and test images using Open CV. The error I am receiving is : multiple bounding boxes are being created around one single object.enter image description here

Where the original image(before annotation) is like this: enter image description here

I am giving below the code I used:

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')

Please help me to understand what could possibly be wrong? Thanks in advance!

标签: pythonopencvannotationscv2

解决方案


我自己得到了解决方案;更改“x”的范围(在上面共享的代码中,它给出为:(650>x>130))解决了这个问题


推荐阅读