Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

(RPi Python) Trouble Understanding findContours & drawContours

Hi, I'm further adapting my code and the idea at this testing point is to output the original image and contImage which is meant to be a black image with the contours drawn in white. For some reason they both appear as the original image with the contour overlaid on it.

I'm afraid the several pages of examples I've looked at haven't seemed to help or cleared up my understanding, nor did looking at the definition of each function. Also, the values are stored as an [array[array[y,x]], right? I'll need to know for the next step of development.

Anyway, here's my code as it stands. I've tried replacing newImage with an np.zeros to write a black image to overlay the contours on but that didn't seem to make a difference. I've been coding all day and going even more loopy so your help is appreciated :)

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
image = cv.imread('/home/pi/Desktop/ScannerDev/TestImage.png', cv.IMREAD_GRAYSCALE)
newImage = image


def imageToPoints (image):
    ret, discrImage = cv.threshold (image, 127, 255, 0)
    height, width = discrImage.shape

    # Add a line of white values to the top of the image.
    # This ensures that the binary outer contour works.
    # It is removed later before writing to point cloud.
    # Order is [y,x] i.e. [row, column]
    discrImage[0,:] = 255 # 1st row, and the whole x range

    img, vectImage, heirarchy = cv.findContours(discrImage, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

    return vectImage


if __name__ == '__main__':
    contImage = imageToPoints (image)
    newImage = cv.drawContours(newImage, contImage, -1, (255,255,255), 1)
    while (1):
        cv.imshow ('original', image)
        cv.imshow ('Contoured', newImage)

        c = cv.waitKey(5)
        if 'q' == chr(c & 255):
            break 

    cv.destroyAllWindows