Reputation: 41
I'm trying to convert an image to cmyk array and seperate Cyan,Magentha,Yellow,Black values .Is it possible with python .How to convert image to Rgb array and then to cmyk?
from PIL import Image
im = Image.open('apple.png')
pixels = list(im.getdata())
print (pixels)
i tried the above code but the ide got stuck after running the code.is there any mistake in that code ?(in above code i just print the rgb array only).
Upvotes: 2
Views: 5135
Reputation: 538
Covert to CMYK:
im = Image.open('apple.png').convert('CMYK')
I would recommend numpy
(imported as np
conventionally) for working with the pixel data. Conversion between the two is simple.
Image
->ndarray
: np.array(Image)
ndarray
->Image
: Image.fromarray(ndarray)
So covert your image to an ndarray
:
import numpy as np
np_image = np.array(im)
Let's check the dimensions of the image:
print(np_image.shape) # (rows, columns, channels)
(400, 600, 4)
And finally print the actual pixel values:
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]]]
To get each of the individual channels we can use numpy
slicing. Similar to Python's list slicing, but works across n dimensions. The notation can look confusing, but if you look at the individual slices per dimension it is easier to break down.
# [:, :, 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]
What we have now are four ndarray
s of shape (400, 600) for each of the channels in the original CMYK np_image
.
Upvotes: 4