[Python] Count the total number of two different objects in an image

Discussão em 'Python' iniciado por Stack, Setembro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to count the total number of small rice and big rice in this image src, and to the best that I could, I was able to contour this contoured.

    This is my code btw

    rice_grain, adlai = 0, 0

    src = cv2.imread('./A1.png')
    img_gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.GaussianBlur(img_gray, (7,7), 0)


    img_thresh, output_img_thresh = cv2.threshold(img_blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)


    contours, hierarchy = cv2.findContours(output_img_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
    area = cv2.contourArea(contour)
    if area > 400:
    adlai += 1
    cv2.drawContours(src, [contour], -1, (0,255,0), 2)
    elif area > 50:
    rice_grain += 1
    cv2.drawContours(src, [contour], -1, (0,0,255), 2)

    print(f"Adlai grains: {adlai}")
    print(f"Rice grains: {rice_grain}")

    cv2.imshow('Grains Counted', src)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


    I have tried using thresholding and binarization. Manually counting the grains the big ones should be around 42 and the small ones are 28.

    Any suggestions as to what I could do? I believe that this problem is arising on how I contour the grains.

    Continue reading...

Compartilhe esta Página