Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Numpy array to image by using CV2 or PIL

I am trying to convert my array to image using CV2 or PIL libraries, In both of libraries, I am getting the images with mixed up color.

This is the way I tried convert Numpy array to image using CV2:

   for i in range(len(batch_tx)):
        cls_pred = sess.run(y_pred_cls, feed_dict={x: batch_tx})
        cls_true = sess.run(tf.argmax(batch_ty, 1))
        img = cv2.resize(batch_tx[i], (FLAGS.img_size, FLAGS.img_size))
        img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_BGR2RGB)
        cv2.imwrite(
            './saveImage/img' + str(i) + ': ' + 'True: ' + str(cls_true[i]) + ', Pred:' +
            str(cls_pred[i]) + '.JPEG', img)

The output is like below image for all my images (This is an image of a ship)

enter image description here

And I have tried PIL library as well and got the same output.

batch_tx[1] is an array of the first image in my dataset and the type is numpy.ndarray with the shape of (96,96,3)

Any Idea?

Thanks in advance.

like image 737
A.M Avatar asked Jun 04 '18 11:06

A.M


1 Answers

Most of OpenCV functions work only with BGR images and not RGB, for example imshow or imwrite. OpenCV will do the work for you to put it in the correct way and save it as JPG image that can be loaded by ANY other app. If you have it with another order, then the function won't know this and save it with the wrong order.

Removing this line:

img = cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_BGR2RGB)

should do the work for you.

My guess is that is not in the correct format (np.uint8) either, since you use it in the line that I just told you to remove. So you must also change the saving part to:

cv2.imwrite(
            './saveImage/img' + str(i) + ': ' + 'True: ' + str(cls_true[i]) + ', Pred:' +
            str(cls_pred[i]) + '.JPEG', img.astype(np.uint8))

Everything should work now. This images can be loaded in another moment with PIL an any other library as well and you will get almost identical images (JPG is a lossy compression) if you want identical, try saving them in another format that has lossless compression.

like image 113
api55 Avatar answered Sep 25 '22 18:09

api55