【问题标题】:Is there any problems in Image.open(os.path.join(origin_path,name)).convert('P')?Image.open(os.path.join(origin_path,name)).convert('P') 有什么问题吗?
【发布时间】:2020-01-01 18:42:35
【问题描述】:

我通过opencv更改了pascal数据集中的一些图像,然后我需要将它们转换为P模式。 我用img = Image.open(os.path.join(origin_path,name)).convert('P')将RGB图像转换为P模式。但是新图像有点奇怪。为什么新图像的颜色不像原来的那样平滑? 它对我的训练有害吗?我该如何处理?

原图

新图片

【问题讨论】:

  • 您的原始图像已经是调色板图像。
  • 是的,问题出在我用cv2改变像素,然后用imwrite保存图像。但是它是RGB,在训练过程中不能工作。所以我需要转换RGB到调色板。我没有找到opencv方法来做。所以我使用了img = Image.open(os.path.join(origin_path,name)).convert('P')。但是效果不好
  • 我不明白。您的原始图像已经是调色板图像 - 您无需使用 OpenCV 或 PIL 打开它即可将其转换为调色板图像,因为它已经是调色板图像。
  • 因为我需要更改原始图像的一些像素以将某些颜色部分更改为另一种颜色。比如将 [0,128,0] 更改为 [0, 0, 0]

标签: computer-vision python-imaging-library


【解决方案1】:

哦,我明白了。您想修改调色板。你可以这样做:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Load the source image
im  = Image.open('original.png') 

# Extract the palette into a Numpy array and reshape as 256 RGB triplets
palette = np.array(im.getpalette())
colorVectors = np.reshape(palette,(-1,3))

# Replace any palette entries consisting of [192,128,128] with yellow [255,255,0]
colorVectors[np.all(colorVectors==[192,128,128],axis=-1)] = [255,255,0]

# Put modified palette into image and save
im.putpalette(colorVectors.ravel().tolist())     
im.save('result.png')

原图

输出图像


如果您知道要更改特定的调色板条目,并且知道它是条目0,您可以这样做:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Load the source image
im  = Image.open('original.png') 

# Extract the palette into a Numpy array and reshape as 256 RGB triplets
palette = np.array(im.getpalette())
colorVectors = np.reshape(palette,(-1,3))

# Make palette entry 0 into magenta
colorVectors[0]=[255,0,255]

im.putpalette(colorVectors.ravel().tolist())
im.save('result.png') 


关键字:Python、PIL、Pillow、调色板、托盘化、PNG、修改调色板、更改调色板、更改调色板、替换调色板、图像、图像处理。

【讨论】:

    猜你喜欢
    • 2013-11-05
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多