python - 使用当前颜色间隔快速查找像素位置

标签 python image opencv pygame python-imaging-library

我遇到了用当前颜色间隔查找像素位置的问题。 这很慢:

def inRange(self, tgColor, excColor, jump):
    if tgColor[0] > excColor[0] - jump and tgColor[0] < excColor[0] + jump and tgColor[1] > excColor[1] - jump and tgColor[1] < excColor[1] + jump and tgColor[2] > excColor[2] - jump and tgColor[2] < excColor[2] + jump:
           return True
    return False

 for iy in xrange(self.pilImage.size[1]):
        for ix in xrange(self.pilImage.size[0]):
            if self.inRange(data[ix, iy], self.targetColor, self.jump):

所以,你能帮我改进这段代码,让它运行得更快吗? (图像尺寸 - 640 x 480) 也许是另一个库:OpenCV、pygame、PIL?

最佳答案

你的代码可能 super 慢

OpenCV 自带函数cv2.inRange() .您传递最小和最大像素值,您将获得一个二值图像,其中通过的像素为白色,失败的像素为黑色。

然后你可以使用numpy.where()找到白色像素的索引。

下面是一个灰度值的例子。它也可以扩展到彩色图像。 [Link]

例子:

>>> import cv2
>>> import numpy as np
>>> x = np.random.randint(1,10, (5,5))
>>> x
array([[9, 5, 1, 3, 1],
       [7, 7, 2, 1, 7],
       [9, 1, 4, 7, 4],
       [3, 6, 6, 7, 2],
       [3, 4, 2, 3, 1]])
>>> y = cv2.inRange(x,4,8)
>>> y
array([[  0, 255,   0,   0,   0],
       [255, 255,   0,   0, 255],
       [  0,   0, 255, 255, 255],
       [  0, 255, 255, 255,   0],
       [  0, 255,   0,   0,   0]], dtype=uint8)

>>> z = np.transpose(np.where(y>0))
>>> z
array([[0, 1],
       [1, 0],
       [1, 1],
       [1, 4],
       [2, 2],
       [2, 3],
       [2, 4],
       [3, 1],
       [3, 2],
       [3, 3],
       [4, 1]])

关于python - 使用当前颜色间隔快速查找像素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147259/

相关文章:

python - python 正则表达式代码大小超出限制

java - 如何使用 JTable 鼠标单击事件将图像从 JTable 显示到 JLabel 或从数据库显示到 JLabel?

python - 使用 Python Opencv 在图像中查找问题文本 block

python - 加载 TrueType 字体到 OpenCV

c - opencv calcHist错误

python - 将 psycopg2 DictRow 查询转换为 Pandas 数据框

python - Python 中的链表 - Append、Index、Insert 和 Pop 函数。不确定代码/错误

python - 2 人骰子游戏,其中偶数总得分和奇数总失分 NEA 任务计算机科学

html - 为什么图像离开了页面,而没有其他内容

c++ - 如何以编程方式识别视频中更改的帧