[英]How to convert tensorflow image Tensor to Numpy array inside Dataset?
I want to create some image mask during image augmentation.我想在图像增强期间创建一些图像蒙版。 Example image
示例图片
Code:代码:
import tensorflow as tf
import cv2
import pandas
# You can replace to local image
train_df = pd.DataFrame({'image_id': ['https://i.stack.imgur.com/CMEaA.jpg'],
'label': [1]})
def create_mask(image, label):
print(type(image)) # <class 'tensorflow.python.framework.ops.Tensor'>
if isinstance(image, str):
img = cv2.imread(image)
else:
img = image
## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
## mask of green (36,0,0) ~ (70, 255,255)
mask1 = cv2.inRange(hsv, (36, 0, 0), (70, 255,255))
## mask o yellow (15,0,0) ~ (36, 255, 255)
mask2 = cv2.inRange(hsv, (15,0,0), (36, 255, 255))
## final mask and masked
mask = cv2.bitwise_or(mask1, mask2)
result = cv2.bitwise_and(img,img, mask=mask)
return result, label
train_ds = tf.data.Dataset.from_tensor_slices((
train_df.image_id.values,train_df.label.values))
train_ds = train_ds.map(create_mask)
As result I get error because we have a tensor in the "image":结果我得到错误,因为我们在“图像”中有一个张量:
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
TypeError: Expected Ptr<cv::UMat> for argument 'src'类型错误:参数“src”的预期 Ptr<cv::UMat>
Ok, we need a numpy array.好的,我们需要一个 numpy 阵列。 But if I try img = image.numpy() I got error:
但是如果我尝试 img = image.numpy() 我得到了错误:
AttributeError: 'Tensor' object has no attribute 'numpy' As expected... AttributeError: 'Tensor' object 没有属性 'numpy'正如预期的那样......
Also I tried eval() with sess.run() but got error for placeholder, something like "tensor unhashable, use tensor.ref()", but if I use ref(), I get something like "cannot use Tensor".我还尝试了 eval() 和 sess.run(),但占位符出现错误,例如“张量不可散列,使用 tensor.ref()”,但如果我使用 ref(),我会得到类似“无法使用张量”的信息。
Well, I have one simple question - can anybody advice me a working way to convert Tensor to numpy array during image process inside tf.data.Dataset?好吧,我有一个简单的问题 - 在 tf.data.Dataset 中的图像处理期间,任何人都可以建议我一种将张量转换为 numpy 数组的工作方法吗?
Try using only Tensorflow functions.尝试仅使用 Tensorflow 函数。 For example, you can use
tf.image.rgb_to_hsv
.例如,您可以使用
tf.image.rgb_to_hsv
。
rgb = tfio.experimental.color.bgr_to_rgb(img)
hsv = tf.image.rgb_to_hsv(rgb)
You should find a Tensorflow way to do the following operations too.您也应该找到一种 Tensorflow 方法来执行以下操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.