![](/img/trans.png)
[英]How to apply an operation to every PIXEL (not every rgb component!) of a python image (either using numpy, opencv or PIL)?
[英]Searching for a pixel in an image using opencv, numpy and python
我已經能夠讀取圖像,然后使用工作正常的坐標位置讀取特定像素( pixel = img[801,600]
)。
我的下一步是遍歷每個像素並嘗試使用像素數據找到位置(在本例中為 [801,600])。
我通過“img”的迭代無法找到像素。 我將不勝感激任何幫助或指導。
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
迭代功能將為您提供幫助。 它將提供一個迭代索引,在您的情況下,將提供一個像素索引:
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
方法,因為它們已針對此類應用程序進行了優化:
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()
我認為您遇到的主要問題是您需要定義圖像的width
和height
,以便您知道需要在 x 和 y 方向上循環多少像素
# 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))
您的語句if x.sort ==pixel.sort
正在測試x
對象上的sort
方法是否與pixel.sort
函數相等(引用相等)。 它們永遠不會相等,因為它們位於不同的對象上。 我不完全確定您為什么使用sort
方法來測試相等性。 您應該能夠檢查if (x == pixel).all()
並獲得您正在尋找的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.