Searching For A Pixel In An Image Using Opencv, Numpy And Python
Solution 1:
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 fordefsearch_for():
for iidx, i inenumerate(img):
for xidx, x inenumerate(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 fordefsearch_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 indicesprint("\n".join([f"SUCCESS - {idx}"for idx in np.argwhere(diff == 0)]))
if __name__ == "__main__":
print("Search using numpy methods...")
search_array()
Solution 2:
I think the main issue that you are having is that you need to define the width
and height
of your image, so you know how many pixels in the x and y direction you need to loop
# grab the image dimensions
h = img.shape[0]
w = img.shape[1]
point_found_at = []
# loop over the image, pixel by pixel
for y in range(0, h):
for x in range(0, w):
if (x == 801) and (y == 600):
print ("SUCCESS")
point_found_at.append((x, y))
Solution 3:
Your statement if x.sort ==pixel.sort
is testing if the sort
method on the x
object is equal (referential equality) to the pixel.sort
function. These will never be equal because they're on different objects. I'm not totally sure why you're using the sort
method to test equality. You should be able to just check if (x == pixel).all()
and get what you're looking for.
Post a Comment for "Searching For A Pixel In An Image Using Opencv, Numpy And Python"