PIL图像库加载并保存更改的像素值

发布于 2025-02-09 00:43:10 字数 638 浏览 3 评论 0原文

我目前正在研究图像细分问题。作为预处理的一部分,我正在尝试为2类[0,1]创建掩码值。
虽然保存加工的张量并将其加载回去产生不同的掩码值。
我目前的猜测是在引擎盖PIL归一化像素值的下方。
如果是这样,我该如何阻止它做?

我在下面创建了一个简单的示例来解释相同的内容。

tensor_img = torch.where(torch.Tensor(250,250,3) > 0, 1, 0)
img_arr = tensor_img.numpy().astype(np.uint8)
np.unique(img_arr, return_counts=True)

(array([[0,1],dtype = uint8),阵列([[148148,39352])))

img = Image.fromarray(img_arr) 
img.save("tmp.jpg")

#read saved image
img = PIL.create("tmp.jpg")
tensor(img).unique(return_counts=True)

(张量([0,1],dtype = Type = Torch.uint8),张量([62288,212]))))))))))))))))))))))

I am currently working on an Image segmentation problem. As part of preprocessing, I'm trying to create mask values for 2 classes [0, 1].
While, saving the processed tensor and loading them back produces different mask values.
My current guess is under the hood PIL normalizing pixel values.
If so how do I stop it from doing?

I have created below a simple example explaining the same.

tensor_img = torch.where(torch.Tensor(250,250,3) > 0, 1, 0)
img_arr = tensor_img.numpy().astype(np.uint8)
np.unique(img_arr, return_counts=True)

(array([0, 1], dtype=uint8), array([148148, 39352]))

img = Image.fromarray(img_arr) 
img.save("tmp.jpg")

#read saved image
img = PIL.create("tmp.jpg")
tensor(img).unique(return_counts=True)

(tensor([0, 1], dtype=torch.uint8), tensor([62288, 212]))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心 2025-02-16 00:43:10

对于此简单情况(只有2个类),您需要使用png而不是jpeg,因为jpeg是一种有损的压缩和PNG是无损的。

tensor_img = torch.where(torch.Tensor(250,250,3) > 0, 1, 0)
img_arr = tensor_img.numpy().astype(np.uint8)
np.unique(img_arr, return_counts=True)

(array([[0,1],dtype = uint8),阵列([[159189,28311]))(张量([[0,1

img = Image.fromarray(img_arr) 
img.save("tmp.png")

#read saved image
img = np.array(Image.open("tmp.png"))
torch.tensor(img).unique(return_counts=True)

,dtype = type = Torch.uint8),张量([159189,28311]))

] 类是使用颜色地图。

For this simple case (only 2 classes), you need to work with png and not jpeg since jpeg is a lossy compression and png is lossless.

tensor_img = torch.where(torch.Tensor(250,250,3) > 0, 1, 0)
img_arr = tensor_img.numpy().astype(np.uint8)
np.unique(img_arr, return_counts=True)

(array([0, 1], dtype=uint8), array([159189, 28311]))

img = Image.fromarray(img_arr) 
img.save("tmp.png")

#read saved image
img = np.array(Image.open("tmp.png"))
torch.tensor(img).unique(return_counts=True)

(tensor([0, 1], dtype=torch.uint8), tensor([159189, 28311]))

For more classes it is preferred to work with color map.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文