我遇到了用当前颜色间隔查找像素位置的问题。 这很慢:
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/