Question about when I convert a numpy array to a taichi tensor

在转换一个numpy数组为taichi的tensor之后, numpy数组中的值和tensor中的值为什么不一样呢?

Code example:

# 1. 用PILLOW加载一个四通道(rgba)的图片
imagePath = r"example.png"
image = Image.open(imagePath)

# 2. image => numpy => tensor
numpyArray  = np.array(image)
tensor = ti.field(ti.f32, (image.width, image.height,4)) 
tensor.from_numpy(numpyArray)

# 3. 打印tensor中位于(100,100)像素的四通道值, 结果为[-47.0 51.0 74.0 -1.0]
print(tensor[100,100,0], tensor[100,100,1], tensor[100,100,2], tensor[100,100,3])

# 4. 打印numpy数组中, 位于(100,100)的四通道值. 结果为[209  51  74 255]
print(numpyArray[100,100])

# 问题, tensor和numpy中的值为什么不一样? 
结果看起来第一个值和第四个值不同, 而第二和第三个值相同(51, 74).换了几个位置都是这个规律.

注意到
209 + 47 = 256
255 + 1 = 256
可见是uint8被错误地当作了带符号的int8来转换。

感谢你反馈这个问题,我们会尽快进行修复并争取在下一个版本中发布 :smile:
目前的版本中这样可以临时解决问题:

# 2. image => numpy => tensor
numpyArray  = np.array(image, np.uint32)  # 扩大为 32 位,防止太极发生不当的类型转换

P.S.: @k-ye @yuanming 话说这是不是和最近的 type system 项目有关?

1 个赞

@archibate 应该无关,type没有修改原始的类型转换规则

1 个赞