numpy - 将图像转换为 rgb 数组并使用 python 将其转换为 CMYK 数组
问题描述
我正在尝试将图像转换为 cmyk 数组并分离 Cyan、Magentha、Yellow、Black 值。python 是否可以。如何将图像转换为 Rgb 数组,然后转换为 cmyk?
从 PIL 导入图像
im = Image.open('apple.png')
像素=列表(im.getdata())
打印(像素)
我尝试了上面的代码,但运行代码后 ide 卡住了。该代码有什么错误吗?(在上面的代码中,我只打印 rgb 数组)。
解决方案
转换为 CMYK:
im = Image.open('apple.png').convert('CMYK')
我建议numpy
(np
按惯例导入)处理像素数据。两者之间的转换很简单。
Image
-> ndarray
:np.array(Image)
ndarray
-> Image
:Image.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
。
推荐阅读
- reactjs - 在 Next.js 中使用 FileViewer 时出现运行时错误
- linux - GitLab CI/CD:这项工作没有痕迹。& 没有工作日志
- c++ - 有没有办法从 C++ 中的函数返回自定义结构?
- javascript - 币安链钱包扩展问题
- vaadin - Vaadin Flow:如何将类名添加到模板
- python - 在 python 中显示来自 mysql 的数据时,时间和日期列看起来几乎不可读。有没有办法以日期和时间格式显示它?
- twitter - Tweepy 机器人正在回复所有转发或回复特定用户推文的人
- python - 如何在 Python 中制作常规计时器?
- kubernetes - 如何创建 kubernetes 作业规范来运行 perl 脚本?
- vue.js - 在 Nuxt 中更改路线后如何不向下滚动页面?