使用opencv,numpy和python搜索图像中的像素 [英] Searching for a pixel in an image using opencv, numpy and python

查看:493
本文介绍了使用opencv,numpy和python搜索图像中的像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经能够读取图像,然后使用可以正常工作的坐标位置(pixel = img[801,600])读取特定像素.

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]).

下一步是遍历每个像素,并尝试使用像素数据查找位置(在本示例中为[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.

我通过"img"进行的迭代找不到像素. 我将不胜感激.

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")

推荐答案

内置的enumerate迭代功能将为您提供帮助.它将提供一个迭代索引,在您的情况下,将提供一个像素索引:

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()

也就是说,for循环在python中很慢,并且代码需要花费一些时间才能在适当大的图像上运行.相反,首选使用np.array方法,因为它们已针对此类应用程序进行了优化:

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()

这篇关于使用opencv,numpy和python搜索图像中的像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆