![](/img/trans.png)
[英]OpenCV reads an image as a 3-channel image while PIL reads the same image as a 1-channel image
[英]Find pixel with specific values in its all 3-channel in an image
我有 3 個通道的圖像。 我有 3 個通道的像素值,如果一個像素在其 3 個通道中具有這 3 個值,則它屬於“A”類。 例如
classes_channel = np.zeros((image.shape[0], image.shape[1], num_classes))
pixel_class_dict={'0': [128, 64, 128], '1': [230, 50, 140]} #num_classes=2
for channel in range(num_classes):
pixel_value= pixel_class_dict[str(channel)]
for i in range(image.shape[0]):
for j in range(image.shape[1]):
if list(image[i][j])==pixel_value:
classes_channel[i,j,channel]=1
基本上我想生成一個通道數組,該數組等於類數,每個類在特定通道中分開。 有什么有效的方法可以做到這一點嗎?
您可以使用 numpy 的廣播來更有效地檢查頻道中的任何值是否與另一個值匹配:
>>> a=np.arange(2*3).reshape(2,3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> a == 4
array([[False, False, False],
[False, True, False]])
這樣您就可以創建二進制掩碼。 還有那些可以與布爾運算符結合使用的運算符,例如np.logical_and
和np.logical_or
:
>>> b = a == 4
>>> c = a == 0
>>> np.logical_and(b, c)
array([[False, False, False],
[False, False, False]])
>>> np.logical_or(b, c)
array([[ True, False, False],
[False, True, False]])
在您的情況下,您可以遍歷像素值的類別,並比較不同的通道:
>>> pixel_class_dict = {1: [18, 19, 20], 2: [9,10,11]}
>>> a = np.arange(2*4*3).reshape(2,4,3)
>>> b = np.zeros((a.shape[:2]), dtype=np.int)
>>> for pixel_class, pixel_values in pixel_class_dict.items():
... mask = np.logical_and(*(a[..., channel] == pixel_values[channel]
... for channel in range(a.shape[-1])))
... b += pixel_class*mask
...
>>> b
array([[0, 0, 0, 2],
[0, 0, 1, 0]])
最后一部分有效,因為您可以將數字與布爾值相乘( 4*True == 4
和3*False == 0
並且因為我假設您字典中的每個像素值都是唯一的。如果后者不不,您將總結類標識符。
稍微短一點的方法是重塑起始數組:
>>> b = np.zeros((a.shape[:2]), dtype=np.int)
>>> a2 = a.reshape(-1, 3)
>>> for pixel_class, pixel_values in pixel_class_dict.items():
... mask = (np.all(a2 == pixel_values, axis=1)
... .reshape(b.shape))
... b += mask * pixel_class
...
>>> b
array([[0, 0, 0, 4],
[0, 0, 2, 0]])
找到另一個解決方案:這里的圖像是我們想要的圖像(具有 3 個通道)
import numpy as np
import cv2
for class_id in pixel_class_dict:
class_color = np.array(pixel_class_dict[class_id])
classes_channel[:, :, int(class_id)] = cv2.inRange(image,class_color,class_color).astype('bool').astype('float32')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.