Home > Back-end >  opencv count rectangle that frame divided into 4 section
opencv count rectangle that frame divided into 4 section

Time:06-08

I have a haar cascade project that counts cars from video frame by frame, and I start wondering is it possible to divide 1 frame into 4 sections and count the car for each section. For example, I have this frame.

frame

as you can see this frame has 4 screens/sections and I want the haar cascade count the car for each section, but the algorithm that I created only count for 2 section (above and below screens)

    for (x,y,w,h) in cars:
        cv2.rectangle(img,(x,y),(x w,y h),(0,0,255),2)
        # divide screen for 4 screen and count the car
        if x < img.shape[1]/2:
            car_count1  = 1
        elif x < img.shape[1]/2*3:
            car_count2  = 1
        elif x < img.shape[1]/2*5:
            car_count3  = 1
        else:
            car_count4  = 1

result

For "screen 1" is the above screen that has 8 rectangles, and "screen 2" for below screen that has 13 rectangles. I know the problem is from the elif x < img.shape[1]/2*5: and else:, but I don't know the right condition for this problem.

Thanks

CodePudding user response:

Well first of all you probably want to use the centerpoint of your rectangles to count it for the right frame

centerx = x w/2
centery = y h/2

Your image areas are x < 0.5width and also y < 0.5height for the top left, x > 0.5width and y < 0.5height for top right and so on.

if centerx < img.shape[1]/2 and centery < img.shape[0]/2:
    count1  = 1
if centerx >= img.shape[1]/2 and centery < img.shape[0]/2:
    count2  = 1
if centerx < img.shape[1]/2 and centery >= img.shape[0]/2:
    count3  = 1
if centerx >= img.shape[1]/2 and centery >= img.shape[0]/2:
    count4  = 1
  • Related