![](/img/trans.png)
[英]plt.imshow() doesn't show proper masked array(np.ma.masked_where())
[英]Can't show picture with plt.imshow
我想 plot 存儲在 numpy 數組 x_val 但 plt.imshow(val[1]) 中的一系列圖像。 另一方面,使用 opencv 它可以正常工作:
cv2.imshow('image', x_val[1])
cv2.waitKey(0)
cv2.destroyAllWindows()
從我到目前為止所讀到的內容來看,我認為問題在於圖像當前處於 BGR 並且必須轉換為 RGB(如果我錯了,請糾正我)。 所以我嘗試了以下方法:
img = cv2.imshow('image', x_val[1])
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
但我收到了這個錯誤信息:
File "C:\Users\Maximal\Documents\Python\PyCharm\TrafficSignClassification\model\trafficSignsClassification.py", line 156, in evaluateTestData
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'
我嘗試的另一件事是這種方法:
img = np.array(x_val[1], dtype=np.uint8)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
這並沒有給我一個錯誤,但圖片只是黑色的。 我究竟做錯了什么?
編輯:我首先對圖片所做的事情如下:
def preprocessData(self, x_train, x_val, y_train, y_val):
# --- normalize images ---
def normalize(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Grayscale image
img = cv2.equalizeHist(img) # Optimize Lightning
img = img / 255.0 # Normalize px values between 0 and 1
return img
for x in range(len(x_train)):
x_train[x] = normalize(x_train[x])
for x in range(len(x_val)):
x_val[x] = normalize(x_val[x])
# --- transform the data to be accepted by the model ---
y_train = np.array(y_train)
y_val = np.array(y_val)
x_train = np.array(x_train)
x_val = np.array(x_val)
x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)
x_val = x_val.reshape(x_val.shape[0], x_val.shape[1], x_val.shape[2], 1)
print("preprocessing data done.")
return x_train, x_val, y_train, y_val
我在 TF2 中使用 CNN 中的圖片,所以我必須分別轉換它們。 我可以在轉換前使用 plt.imshow() plot 圖片沒有問題。 但在此 function 之后,只有 cv2.imshow() 有效
我自己找到了答案。 我必須將這些值乘以 255 才能獲得正確的圖像。 在所有值都介於 0 和 1 之間之前,這會導致黑色圖像。
img = np.array(x_val[i]*255, dtype=np.uint8)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.imshow(img)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.