Machine learning error solution 2——ValueError: too many values to unpack (expected 3)

Reference material: blue bird

In the process of learning Pytorch's PIL module, I ran the following code:

from PIL import Image
a = Image.open('Avengers.jpeg')
ra, ga, ba = a.split() # 把图像分割为R,G,B三个通道图像
ra.save("R.jpg")
ga.save("G.jpg")
ba.save("B.jpg")

The general meaning is to divide an RGB image into three channels of R, G, and B, and save the image of each channel separately.

But the following error occurred:

Please add a picture description

ValueError: too many values to unpack (expected 3)

The translation is that the number of variables used to receive is inconsistent with the number of variables that the function needs to receive.

I searched for a blog for a long time, and finally found a blog problem description that matches mine (that is, the link given at the back of the reference)

The problem is that the image 'Avengers.jpeg' does not necessarily have only three channels!

So I add a line of code after the second line:

print(a.mode, a.size, a.format)

The output is:

RGBA (600, 299) PNG

Here the output is RGBA not RGB! RGBA mode has four color channels, so it should be received by four variables.

The modified code is as follows:

from PIL import Image
a = Image.open('Avengers.jpeg')
print(a.mode, a.size, a.format)
ra, ga, ba, aa = a.split()  # 把图像分割为R,G,B三个通道图像
ra.save("R.jpg")
ga.save("G.jpg")
ba.save("B.jpg")
aa.save("A.jpg")

Running results: Four new pictures have been added to the folder of this directory, but except for the white picture of 'A.jpg', the other three pictures are all gray (I guess it is a grayscale picture, only one is saved when saving digital value, then the system defaults to a grayscale image with only one channel)

Please add a picture description

I haven't found a solution so far, so I call the pylab module

from PIL import Image
from pylab import subplot, imshow, show
a = Image.open('Avengers.jpeg')
ra, ga, ba, aa = a.split()  # 把图像分割为R,G,B三个通道图像
subplot(221)
imshow(ra)
subplot(222)
imshow(ga)
subplot(223)
imshow(ba)
subplot(224)
imshow(aa)
show()

operation result:

Please add a picture description

Guess you like

Origin blog.csdn.net/m0_61787307/article/details/127288117