简体   繁体   English

如何在张量流中将图像张量转换为 numpy 数组?

[英]How to convert image tensor in to numpy array in tensorflow?

I am training a CNN to generate images.我正在训练一个 CNN 来生成图像。 The type of all the images are tensors.所有图像的类型都是张量。 I want them to be converted into numpy arrays then I can process them using opencv.我希望它们被转换成 numpy 数组,然后我可以使用 opencv 处理它们。

I know about the .numpy() method, it converts my tensor into an numpy array but the shape is still tensor.我知道.numpy()方法,它将我的张量转换为一个 numpy 数组,但形状仍然是张量。 I can't get it to work in cv2.我无法让它在 cv2 中工作。

Here is my code:这是我的代码:

p=model_(x) 
s=p.numpy()
print(s.shape)
cv2.imwrite("hello.jpg",s)

(1, 183, 275, 3), this is the shape of the array generated using .numpy() , how can I change its shape to retain output image? (1, 183, 275, 3),这是使用.numpy()生成的数组的形状,如何更改其形状以保留输出图像?

You need to get rid of the first dim (batch), just use slicing with reshape .您需要摆脱第一个昏暗(批次),只需使用reshape切片。

s=p.numpy()
print(s.shape)
cv2.imwrite("hello.jpg",s.reshape(s.shape[1:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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