使用PIL将图片转换为rgb数组,然后手动将其转换为CMYK数组

时间:2018-10-18 12:03:49

标签: python numpy python-imaging-library

我正在尝试将图像手动转换为cmyk数组并重建图像,但是我没有得到任何图像,所以我决定分离c,m,y,k并显示它,但没有合适的图像.so我只是试图将每个数据保存在文件中以进行验证,我找不到该数据中的任何错误。有人可以告诉我为什么会发生这种错误以及我在这里所做的错误是什么。 >

from PIL import Image
import numpy as np

im = Image.open('idcard.jpg').convert('RGB')
np_image = np.array(im)
num_list = np_image.tolist()
print( len(num_list))
str1 =str(num_list)
print( len(str1))
f=open("idcardforgb.txt","w")
f.write(str1)
f.close()

cyan = 0
magenta = 0
yellow = 0
key = 0
cmyk_scale = 255
t=np.shape(np_image)
print (t)
i=(int)(t[0])
j=(int)(t[1])
k=(int)(t[2])

c_final=[[[0 for f in range(4)]for g in range(j)]for h in range(i)]

for z in range(i):
    temp_z=z
    for y in range(j):
        temp_y=y
        for x in range(3):
            if x==0:
                r = np_image[z][y][x]
            if x==1:
                g = np_image[z][y][x]
            if x==2:
                 b = np_image[z][y][x]
        if (r == 0) and (g == 0) and (b == 0):
            cyan=0
            magenta=0
            yellow=0
            key=cmyk_scale
            c_final[temp_z][temp_y][0]=cyan
            c_final[temp_z][temp_y][1]=magenta
            c_final[temp_z][temp_y][2]=yellow
            c_final[temp_z][temp_y][3]=key
        else:
            c = 1 - r / 255.
            m = 1 - g / 255.
            y = 1 - b / 255.
            min_cmy = min(c,m,y)
            c = (c - min_cmy) / (1 - min_cmy)
            m = (m - min_cmy) / (1 - min_cmy)
            y = (y - min_cmy) / (1 - min_cmy)
            k = min_cmy
            cyan =(int) (c*cmyk_scale)
            magenta =(int) (m*cmyk_scale)
            yellow = (int)(y*cmyk_scale)
            key = (int)(k*cmyk_scale)

            c_final[temp_z][temp_y][0]=cyan
            c_final[temp_z][temp_y][1]=magenta
            c_final[temp_z][temp_y][2]=yellow
            c_final[temp_z][temp_y][3]=key

np_image1 = np.array(c_final)
t1=np.shape(np_image1)
print(t1)
cnum_list = np_image1.tolist()
print( len(cnum_list))
str1c =str(cnum_list)
print( len(str1c))
f=open("idcardcmyk.txt","w")
f.write(str1c)
f.close()
im = Image.fromarray(np_image1, mode='CMYK')
im.save('testing.jpg')
##im = Image.fromarray(im, mode="CMYK")
print("test ok")
ct = np_image1[:, :, 0]
cyan_list=ct.tolist()
str_c =str(cyan_list)
f=open("idcard_cp.txt","w")
f.write(str_c)
f.close()
print("test ok")
img= Image.fromarray(ct)
img.save('idcard_c.png')
mt = np_image1[:, :, 1]
imm= Image.fromarray(mt)
imm.save('idcard_m.png')
yt = np_image1[:, :, 2]
imm = Image.fromarray(yt)
imm.save('idcard_y.png')
kt = np_image1[:, :, 3]
imm = Image.fromarray(kt)
imm.save('idcard_k.png')

0 个答案:

没有答案