[Python] How to use opencv to detect the number of items in a picture?

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    I want to get return value "1" for image1, and "2" for image2, (because there is a hand in image2 compared to image1), or at least to get a return value from image2 bigger than the value of image1.

    I have tried the following code:

    import cv2
    import sys

    filename = sys.argv[1]

    # 1. Load and Preprocess Image
    img = cv2.imread(filename)


    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (15, 15), 0)

    cv2.imwrite('gray.jpeg', gray)

    edged = cv2.Canny(gray, 5, 100)
    cv2.imwrite('edged.jpeg', edged)


    # Find the contours of the object
    contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    print(len(contours))


    but it gives "135" for image1, and "62" for image2. The value of image2 is less than that of image1. Some internet posts say YOLO could detect objects, but I tried and it seemed YOLO can only detect predefined classes. Thanks a lot for any response.

    Image 1 [​IMG]

    Image2 [​IMG]

    Continue reading...

Compartilhe esta Página