gpt4 book ai didi

python - 无法使用plt.imshow显示图片

转载 作者:行者123 更新时间:2023-12-02 16:33:49 29 4
gpt4 key购买 nike

我想绘制一系列存储在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()绘制图片,而不会出现问题。但是在此功能之后,只有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)

关于python - 无法使用plt.imshow显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61717906/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com