簡體   English   中英

OpenCV:如何檢測像素顏色變化

[英]Opencv: How to detect pixel color change

我成功地為使用創建的給定圖片着色了我想要的區域

numpy (`img = np.zeros((512,512,3), np.uint8)`).

我使用OpenCV顯示圖片

cv2.imshow()

使用鼠標光標着色后,保存圖片。

如何檢測圖像給定像素的顏色已被修改?

通常,可以使用常用的==<!=等運算符比較兩個數組。 比較返回一個布爾(真/假)數組:

import numpy as np

x = np.array([0, 1, 2, 3, 4])
y = np.array([9, 1, 2, 3, 7])

arrays_equal = x == y

arrays_equal將是一個布爾數組,相等時為True ,不相等時為False

array([False,  True,  True,  True, False], dtype=bool)

但是,還有一個警告,因為您正在處理圖像數據。 最后,您可能想要獲得的是一個2D數組 ,其中任何顏色都發生了變化,但是您正在比較兩個3D數組 ,因此您將獲得一個3D布爾數組作為輸出。

例如:

im = np.zeros((5,5,3), dtype=np.uint8)
im2 = im.copy()

# Change a pixel in the blue band:
im2[0,0,2] = 255

# The transpose here is just so that the bands are printed individually 
print (im == im2).T

這將產生:

[[[ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]]

 [[ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]]

 [[False  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]
  [ True  True  True  True  True]]]

當然,您可能想要的更像是最后一支樂隊。

在這種情況下,您想使用np.all來“減少”事物並獲得2D數組,其中任何像素中的任何顏色都不同。

為此,我們將axis kwarg用作np.all來指定應沿最后一個軸進行比較(在這種情況下, -12是等效的: -1表示“ last”):

np.all(im == im2, axis=-1)

產生:

array([[False,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True]], dtype=bool)

還要注意,如果需要“翻轉”此數組,則可以將!=運算符與np.any而不是np.all或者可以使用~ (邏輯運算符不為numpy)取反。 例如opposite = ~boolean_array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM