[Python] Crop from image using OpenCV without including green - OpenCV & Python

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    Recently began developing a basic ANPR application using OpenCV and PyTesseract. The overall contouring and cropping seems to work but there is a glaring problem in that i'm unable to figure out how to remove the green from the image.

    The following code is what i'm currently using:

    image = f'home/folder/car.jpg'
    image = cv2.imread(image)

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #frame filtered again
    canny = cv2.Canny(gray, 100, 200)

    contours, _ = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(image, contours, -1, (0, 255, 0), 3)

    for contour in contours:
    approx = cv2.approxPolyDP(contour, 0.02 * cv2.arcLength(contour, True), True)

    if len(approx) == 4:
    x, y, w, h = cv2.boundingRect(approx)

    aspectratio = w / float(h) #aspect ratio
    area = w * h

    if 2 < aspectratio < 5 and area > 2000:
    cropped = image[y:y+h, x:x+w]
    cv2.imwrite('contour.png', cropped)


    car.jpg. No filters:

    [​IMG]

    car.jpg. Contoured:

    [​IMG]

    car.jpg. Contoured and Cropped:

    [​IMG]

    I'm fairly new to openCV and Python and i'm not exactly a professional programmer so if there's any minor improvements alongside the solution, feel free to add.

    Continue reading...

Compartilhe esta Página