I am working on a project for a Raspberry Pi that requires some image processing.

The aim is to find a white line on a black background by finding the weighted mean in each row/column. However to avoid this being skewed by other parts of the path that may also be in the picture I want to restrict the mean to within a tolerance of the last centroid computed with a known value for the first row/column As a mainly C++ programmer I initially wrote this code using for loops but this is very slow in python.

I have started reading about numpy arrays and vectorisation, however I am struggling to see how I might use them because of the dependency on the previous value calculated. This is my current attempt:

img = Image.open('Test2.png')

img = img.convert('L')
print("Size of image is:")
size = img.size
print(img.format, img.size, img.mode)

pixels = np.asarray(img)
width, height = img.size

average_index_rows = []
average_index_cols = []
tol = 20

for cc in range(0, width):
    min_index = max(0, average_index_cols[cc] - 20)
    max_index = min(height, average_index_cols[cc] + 20)
    sub_array = np.asarray(pixels[cc, min_index:max_index])
    y = sub_array.sum()
    next_centroid = compute_weighted_centroid((sub_array))
    if next_centroid!= next_centroid:

for rr in range(0, height):
    min_index = max(0, average_index_rows[rr]-20)
    max_index = min(height, average_index_rows[rr]+20)
    sub_array = pixels[min_index:max_index, rr]
    next_centroid = compute_weighted_centroid((sub_array))
    if next_centroid!= next_centroid:

img = img.convert('RGB')
img_pixel = img.load()

for rr in range(1, len(average_index_rows)):
    if average_index_rows[rr] != -1:
        current_average_pixel = average_index_rows[rr]

        for pixel in range(-3,3):
            if (current_average_pixel+pixel > 0) and (current_average_pixel+pixel < height):
                img_pixel[rr-1, current_average_pixel+pixel ] = (255,10,10)

for cc in range(1, len(average_index_cols)):
    if average_index_cols[cc] != -1:
        current_average_pixel = average_index_cols[cc]

        for pixel in range(-3,3):
            if (current_average_pixel+pixel > 0) and (current_average_pixel+pixel < width):
                img_pixel[current_average_pixel+pixel, cc-1 ] = (10,255,10)


Is there a better way to formulate this to improve the speed?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.