首页 > 解决方案 > 将图像转换为 rgb 数组并使用 python 将其转换为 CMYK 数组

问题描述

我正在尝试将图像转换为 cmyk 数组并分离 Cyan、Magentha、Yellow、Black 值。python 是否可以。如何将图像转换为 Rgb 数组,然后转换为 cmyk?

从 PIL 导入图像

im = Image.open('apple.png')

像素=列表(im.getdata())

打印(像素)

我尝试了上面的代码,但运行代码后 ide 卡住了。该代码有什么错误吗?(在上面的代码中,我只打印 rgb 数组)。

标签: numpypython-imaging-library

解决方案


转换为 CMYK:

im = Image.open('apple.png').convert('CMYK')

我建议numpynp按惯例导入)处理像素数据。两者之间的转换很简单。

Image-> ndarraynp.array(Image)

ndarray-> ImageImage.fromarray(ndarray)

因此,将您的图像转换为ndarray

import numpy as np

np_image = np.array(im)

让我们检查图像的尺寸:

print(np_image.shape) # (rows, columns, channels)

(400, 600, 4)

最后打印实际的像素值:

print(np_image)

[[[173 185 192   0]
  [174 185 192   0]
  [173 185 192   0]
  ...
  [203 208 210   0]
  [203 209 210   0]
  [202 207 209   0]]
 ...
 [[180 194 196   0]
  [182 195 198   0]
  [185 197 200   0]
  ...
  [198 203 206   0]
  [200 206 208   0]
  [198 204 205   0]]]

为了获得每个单独的通道,我们可以使用numpy切片。类似于 Python 的列表切片,但适用于 n 维。该符号可能看起来令人困惑,但如果您查看每个维度的各个切片,则更容易分解。

# [:,      :,      0] 
#   ^ Rows  ^ Cols  ^ Channel
# The colon alone indicates no slicing, so here we select
# all rows, and then all columns, and then 0 indicates we
# want the first channel from the CMYK channels.

c = np_image[:, :, 0]
m = np_image[:, :, 1]
y = np_image[:, :, 2]
k = np_image[:, :, 3]

ndarray对于原始 CMYK 中的每个通道,我们现在拥有四个形状 (400, 600) np_image


推荐阅读