Skip to content Skip to sidebar Skip to footer

Is It Possible To Detect Pairs Of Connected Pixels?

I'm using OpenCV via Python 3.7. I have a following image (please take note of some red pixels on white areas): I know x and y coordinates of every red pixel in the image. I want

Solution 1:

This answer explains how to use np.count_nonzero() to determine if two points are connected by a white line.

First, draw your image and count the non-zero pixels. There are 18896 non-zero pixels in this example image.

src

import cv2
import numpy as np
import itertools

# Function that converts an image to single channel and counts non-black pixelsdefcount_non_zero(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return np.count_nonzero(gray)

# Create source image
img = np.zeros((456,456, 3), np.uint8)
redCoordinates = [(123,123),(345,123),(345,345)]
cv2.line(img, redCoordinates[0], redCoordinates[1], (255,255,255), 65)
for coordinate in redCoordinates: cv2.circle(img, coordinate, 14, (0,0,255), -1)
# Count the non-zero pixels in the image
base = count_non_zero(img)

Next, iterate through each combination of pairs of red coordaintes. Draw a line between the points. Check if the image has the same number of non zero pixels.

# Iterate through each combination of the redCoordinates
idx = 0
for a,b in list(itertools.combinations(redCoordinates, 2)):
    # Draw a line between the two points
    test_img = cv2.line(img.copy(), a, b, (234,0,234), 5)
    # Recount to see if the images are the sameif count_non_zero(test_img) == base: print(a, b, " are connected.")
    else: print(a,b, " are NOT connected.")

These are some points that are connected:

connected

These are some points that are not connected:

not connected

This is the output of the script:

(123, 123) (345, 123)  are connected.
(123, 123) (345, 345)  are NOT connected.
(345, 123) (345, 345)  are NOT connected.

Post a Comment for "Is It Possible To Detect Pairs Of Connected Pixels?"