-1

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 .

Fianlto
  • 1
  • 3

2 Answers2

0

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
0

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 = []

# Find White so RGB = [255, 255, 255]
rgb_color_to_find = [0xFF, 0xFF, 0xFF]
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))

For gray image just change some thing and you get:

import cv2
import numpy as np

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

color_pixel = []

# Find White in Gray so White = 255 (Max value for uint8)
color_to_find = 255
for i in range(frame.shape[1]):
    tmp_col = np.where(frame[:, i] == color_to_find)

    # 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))
Jay
  • 305
  • 2
  • 11
  • This method is used to search for color images, if only for black and white images, how do I change it? hope you help me – Fianlto Jan 07 '23 at 12:12
  • @Fianlto I edit my message to include a part for gray scale image ! Hope it help you ! – Jay Jan 09 '23 at 09:52