So I have this code:It's detecting objects, and then places a rectangle around the detected object. The problem I have is a white object on white background, it seems to have problems.
![Image]()
![Image]()
Here you see it only detects the edges, or certain parts of the lego piece. I'm surprised it didn't see the entire piece. With this, it more often doesn't see the object than it sees the object. Is there a way to enhance it's detection?
Changing the background is not an option since lego pieces comes in many different colors. I need to be able to see all the pieces regardless of color. Thoughts on this?
Code:
import cv2import numpy as npfrom picamera2 import Picamera2import timedef detect_objects_and_draw(frame, threshold_area): edges = cv2.Canny(frame, 100, 200) contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) object_found = False for contour in contours: area = cv2.contourArea(contour) if area > threshold_area: object_found = True x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) return object_founddef main(): threshold_area = 75 # <-- Adjust this value to tune sensitivity picam2 = Picamera2() config = picam2.create_preview_configuration(main={"size": (640, 480)}) picam2.configure(config) picam2.set_controls({"AfMode": 2}) picam2.start() time.sleep(0.5) print(f"Detecting objects with threshold_area = {threshold_area}. Press 'q' to quit.") while True: frame = picam2.capture_array() detected = detect_objects_and_draw(frame, threshold_area) if detected: print("Object detected!") else: print("No object") cv2.imshow("Camera Feed with Detection", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() picam2.close()if __name__ == "__main__": main()

Here you see it only detects the edges, or certain parts of the lego piece. I'm surprised it didn't see the entire piece. With this, it more often doesn't see the object than it sees the object. Is there a way to enhance it's detection?
Changing the background is not an option since lego pieces comes in many different colors. I need to be able to see all the pieces regardless of color. Thoughts on this?
Statistics: Posted by traderjoe — Mon Aug 11, 2025 7:27 am