Last active
November 18, 2019 13:03
-
-
Save daa233/88ff8957048062d8c08589e95731f505 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Convert an numpy array image to bytes and decode it with tensorflow. | |
# Refers to https://stackoverflow.com/questions/50630045/how-to-turn-numpy-array-image-to-bytes/50630390 | |
import numpy as np | |
import cv2 | |
import tensorflow as tf | |
# img_bgr is an 16-bit BGR image | |
img_bgr = (np.random.rand(50, 50, 3)*65536).astype(np.uint16) | |
cv2.imwrite('demo.png', img_bgr, params=[cv2.CV_16U]) | |
success, img_bytes_arr = cv2.imencode('.png', img_bgr, params=[cv2.CV_16U]) | |
print(img_bytes_arr.dtype, img_bytes_arr.shape) # uint8 (15130, 1) | |
_decode_data = tf.placeholder(dtype=tf.string) | |
_decode = tf.image.decode_png(_decode_data, channels=3, dtype=tf.uint16) | |
# Decode bytes back to an 16-bit RGB image with tensorflow | |
img_rgb_tf = tf.Session().run(_decode, feed_dict={_decode_data: img_bytes_arr.tobytes()}) | |
# Convert img_rgb_tf to BGR color space | |
img_bgr_tf = cv2.cvtColor(img_rgb_tf, cv2.COLOR_RGB2BGR) | |
cv2.imwrite('demo_tf.png', img_bgr_tf, params=[cv2.CV_16U]) | |
print(img_bgr_tf.dtype, img_bgr_tf.shape) # uint16 (50, 50, 3) | |
assert (img_bgr == img_bgr_tf).all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment