Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find a pixel of Specific Color in python

I’m a newbie of python, cv2, numpy.
I want to get coordinate of a pixel which have red color.

I thought np.where can do this plan, but I failed it.
finally, I made something terrible.
but, it works.

Can you give a better choice?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks



    sought = np.array([10, 10, 140])
    gray = np.array([50, 50, 255])

    # print(np.where((img > sought) & (img < gray), 0, img))

    for x in range(img.shape[1]):
        for y in range(img.shape[0]):

            if img[y,x,:][0] > sought[0]:
                if img[y,x,:][1] > sought[1]:
                    if img[y,x,:][2] > sought[2]:
                        if img[y,x,:][0] < gray[0]:
                            if img[y,x,:][1] < gray[1]:
                                if img[y,x,:][2] < gray[2]:
                                    print(x)
                                    print(y)
                                    print("############################################")

>Solution :

This is a better approach:

import numpy as np
import cv2

img = cv2.imread('your_image.jpg')

sought = np.array([10, 10, 140])
gray = np.array([50, 50, 255])

mask = cv2.inRange(img, sought, gray)

coordinates = np.argwhere(mask > 0)
for coord in coordinates:
    x, y = coord
    print("X coordinate:", x)
    print("Y coordinate:", y)
    print("##################")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading