如何在python中将数组转换为图像颜色通道?

How to convert array to image colour channel in python?

我需要将图像的颜色通道(特别是 "Cb")拆分为 8x8 块,以便修改 DCT 系数并稍后重新组合它们。

我正在尝试使用 image.extract_patches_2d()

但是我似乎无法重新组合频道

from PIL import Image
from sklearn.feature_extraction import image
import numpy as np

pic = Image.open('lama.png')
pic_size = pic.size
ycbcr = pic.convert('YCbCr')
(y, cb, cr) = ycbcr.split()


acb = np.asarray(cb)
patches = image.extract_patches_2d(acb, (8, 8))
acb2 = image.reconstruct_from_patches_2d(patches, (500,500))
cb_n = Image.fromarray(acb2, 'L')

即使不做任何补丁重组数组也不对应原来的通道:

cb 另存为图片:

Cb 从补丁恢复(cb_n 在代码中):

那么代码有问题吗?还是无法使用 image.reconstruct_from_patches_2d 从路径(块)恢复颜色通道?

如果是这样,是否有更好的方法来满足我的需要?

感谢阅读,感谢任何帮助。

acb2 上调用 Image.fromarray() 之前,确保将 dtype 更改为 int,因为它在开始时是这样的。 image.reconstruct_from_patches_2d 将您的图片值更改为 float64,而 cb 中的原始值是 uint8。这是我得到的唯一错误来源。除此之外,您的代码按预期工作。

更改您的代码:

acb2 = image.reconstruct_from_patches_2d(patches, (500,500))
cb_n = Image.fromarray(acb2, 'L')

至:

acb2 = image.reconstruct_from_patches_2d(patches, (500,500))
#ADD THIS LINE
acb2 = acb2.astype(np.uint8)
cb_n = Image.fromarray(acb2, 'L')

注意:(与上述无关)

还要确保您在 reconstruct_from_patches_2d 中使用正确的图像尺寸。正如您指定的 (500,500),我假设宽度与高度 (500) 相同。但是在高度和宽度不同的图像中,Image module 将是 column-major 而 numpy(默认情况下 python 数组)是 row -主要。 所以,

pic_size = pic.size

会报告输出(Width, Height),但是在reconstruct_from_patches_2d中使用时,使用(Height, Width)