2017-03-21 50 views
0

我需要在8x8塊中分割圖像的顏色通道(特別是「Cb」),以便修改DCT係數並在稍後重新組合它們。如何將數組轉換爲python中的圖像顏色通道?

我試圖做到這一點使用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保存爲圖像:

enter image description here

CB(代碼CB_N)從補丁修復:

enter image description here

那麼,有沒有什麼毛病的代碼?還是不可能使用image.reconstruct_from_patches_2d從路徑(塊)恢復顏色通道?

如果是這樣,有沒有更好的方式來做我所需要的?

感謝您的閱讀,感謝您的幫助。

回答

1

在致電Image.fromarray()acb2之前,請確保將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將爲列專業而numpy(和默認的python陣列)爲行專業。 所以,

pic_size = pic.size 

將報告輸出(Width, Height),但在reconstruct_from_patches_2d使用時,使用(Height, Width)

+0

非常感謝,它的工作原理! –

相關問題