Home > Back-end >  Python - Find the first white pixel and last one in each column
Python - Find the first white pixel and last one in each column

Time:01-06

how can i find first and last white pixel in a column of binary image . To i calculate distance between points in image

I did but everything is still not resolved , please help me . I have consulted some ways but it's really not as expected .

CodePudding user response:

For a column, you should have something like col = [[p0_r, p0_g, p0_b], ..., [pn_r, pn_g, pn_b]], to find the first and the last white pixels, you should do something like

first_white = col.index([0, 0, 0])
rev = col.copy()
rev.reverse() # reverse the column order
last_white = len(col) - rev.index([0, 0, 0]) - 1

CodePudding user response:

You maybe one something like that and I hope it's help you

import cv2
import numpy as np

frame = cv2.imread("//Path/To/Image.png")

color_pixel = []
rgb_color_to_find = [0x00, 0x00, 0x00]
for i in range(frame.shape[1]):
    # Reverse color_to_find_rgb (2 -> 1 -> 0) cause
    # OpenCV use BGR and not RGB
    tmp_col = np.where(
        (frame[:, i, 0] == rgb_color_to_find[2])
        & (frame[:, i, 1] == rgb_color_to_find[1])
        & (frame[:, i, 2] == rgb_color_to_find[0])
    )

    # If minimum 2 points are find
    if len(tmp_col[0]) >= 2:
        first_pt = (i, tmp_col[0][0])
        last_pt = (i, tmp_col[0][-1])
        distance = tmp_col[0][-1] - tmp_col[0][0]
        color_pixel.append(((first_pt, last_pt), distance))
  • Related