python - 使用 PIL 进行通道替换
问题描述
我目前正在开发一种工具,其中需要将 1 个图像的通道替换为 3 个其他图像。
例如:
I have an image "X" and the channels would be X.r, X.g and X.b respectively.
I have 3 other images ["A","B","C"]
Those 3 images needs to replace the channels in X.
So the result would be X.A, X.B and X.C.
最好的方法是什么?
解决方案
from PIL import Image
img = Image.open('images/image.jpg')
r,g,b = img.split()
#r = img.getchannel(0)
#g = img.getchannel(1)
#b = img.getchannel(2)
img = Image.merge('RGB', (r,g,b))
img.show()
您还可以转换为 numpy 数组并使用数组
from PIL import Image
import numpy as np
img = Image.open('images/image.jpg')
arr = np.array(img)
r = arr[:,:,0]
g = arr[:,:,1]
b = arr[:,:,2]
arr[:,:,0] = r
arr[:,:,1] = g
arr[:,:,2] = b
img = Image.fromarray(arr)
img.show()
例子
from PIL import Image
img1 = Image.open('winter.jpg')
img2 = Image.open('spring.jpg')
r1,g1,b1 = img1.split()
r2,g2,b2 = img2.split()
new_img = Image.merge('RGB', (r1,g2,b2))
new_img.show()
new_img.save('output.jpg')
冬天.jpg
春天.jpg
输出.jpg
推荐阅读
- python - Django - 按表单更新用户实例
- python - 阅读连接查询 Sqlalchemy Jinja
- hadoop - hdfs 或 hadoop 命令在本地到 hdfs 之间同步文件或文件夹
- python - 解析 AWS ATHENA 输出
- elasticsearch - 使用 ElasticSearch 按给定数组排序
- android - 如何在android的存储目录中创建文件夹和文件
- sql-server - 如何在 Spark 和 Zepplin 中使用 SQL JDBC 驱动程序
- python - 用python重命名多个文件名
- c - 将 char* 添加到 char**
- java - 存储包含私钥的json文件