Python - Color detection advice

I have a code working just fine, detecting the blue color as follows and creating a square around the object, like on the top image

But if something gets in between(the pencil in this example), the square goes to the side that is bigger:

Is there a way so even if the pencil gets in between, the code just ignores this noise and the square still works the same as the first example ?

Here’s the code, thanks for reading !

import cv2
import numpy as np
import time


# Camera Connection/Setup
cap = cv2.VideoCapture(0)

cap.set(3, 480)
cap.set(4, 320)
_, frame = cap.read()
rows, cols, _ = frame.shape

x_medium = int(cols / 2)
centerx = int(rows / 2)
centerl = int(cols / 2)
while True:
    _, frame = cap.read()
    hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
    # red color
    low_red = np.array([100, 100, 100])
    high_red = np.array([120, 255, 255])
    red_mask = cv2.inRange(hsv_frame, low_red, high_red)
    contours, _ = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key=lambda x:cv2.contourArea(x), reverse=True)

    for cnt in contours:
        (x, y, w, h) = cv2.boundingRect(cnt)

        x_medium = int((x + x + w) / 2)
   
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        #print("X = ", x)
        #print("Y = ", y)
        #print("\n")
        break

    center = (centerl, centerx)
    cv2.circle(frame, center, 2, (0, 0, 255), -1)

    
    cv2.imshow("Frame", frame)
    cv2.imshow("Mask", red_mask)

    
    key = cv2.waitKey(1)

    if key == 27:
        break
    

cap.release()
cv2.destroyAllWindows()

problem is, that you’ll never know, if you have a ‘split’ contour, or 2 (or more !?) originally seperate objects.

otherwise, you could join the 2 contours (cv2…vconcat())
and get the boundingRect() from that

1 Like

Ohh, didn’t know you could join them, thank you !! There’ll only ever be one object, but possible noises such as discontinuation of the contour, so the concat should work.

… famous last words, hehe :wink: