Searching for a pixel in an image using opencv, numpy and python

JohnPaul :

I have been able to read an image, then read a specific pixel using a co-ordinate location which works fine (pixel = img[801,600]).

My next step is to iterate through each pixel and try to find the location (in this example [801,600]) using the pixel data.

My iteration through "img" isn't able to find the pixel. I would appreciate any help or guidance.

import cv2
import numpy as np

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

pixel = img[801,600]

print (pixel) # pixel value i am searching for

for i in img:
    for x in i:
        if x.sort == pixel.sort:
            print ("SUCCESS")
DBat :

The built-in enumerate iteration function will help you. It will provide an iteration index, that in your case, will provide a pixel index:

import cv2
import numpy as np

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

pixel = img[801,600]
print (pixel) # pixel value i am searching for

def search_for():
    for iidx, i in enumerate(img):
        for xidx, x in enumerate(i):
            if (x == pixel).all():
                print (f"SUCCESS - [{iidx} {xidx}]")

if __name__ == "__main__":
    print("Search using for loops...")
    search_for()

That being said, for loops are slow in python and it takes a while for the code to run on an suitably large image. Instead, using np.array methods are preferred as they are optimized for this type of application:

import cv2
import numpy as np

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

pixel = img[801,600]
print (pixel) # pixel value i am searching for

def search_array():
    # create an image of just the pixel, having the same size of 
    pixel_tile = np.tile(pixel, (*img.shape[:2], 1))
    # absolute difference of the two images
    diff = np.sum(np.abs(img - pixel_tile), axis=2)
    # print indices
    print("\n".join([f"SUCCESS - {idx}" for idx in np.argwhere(diff == 0)]))


if __name__ == "__main__":
    print("Search using numpy methods...")
    search_array()

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=395164&siteId=1