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?
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("############################################")
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("##################")