简体   繁体   中英

Can't show picture with plt.imshow

I want to plot a series of images that are stored in the numpy array x_val but plt.imshow(val[1]) does not work. On the other hand with opencv it works fine:

    cv2.imshow('image', x_val[1])
    cv2.waitKey(0)
    cv2.destroyAllWindows()

From what I've read so far I think the problem is that the image is currently in BGR and has to be transformed to RGB (correct me if I'm wrong). So I tried the following:

img = cv2.imshow('image', x_val[1])
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))

But I got this error message:

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'

One other thing I tried was this approach:

        img = np.array(x_val[1], dtype=np.uint8)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(img)

This did not give me an error but the picture was just black. What am I doing wrong?

EDIT: What I have done with the pictures in the first place was the following:

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

I use the pictures in a CNN in TF2 so I had to transform them respectively. I can plot the pictures with plt.imshow() before the transformation without problems. But after this function only cv2.imshow() works

I found the answer myself. I had to multiply the values by 255 in order to get a proper image. Before all values were between 0 and 1 and this lead to a black image.

        img = np.array(x_val[i]*255, dtype=np.uint8)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(img)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM