Python Pillow 简明教程
Python Pillow - Changing Image Modes
What is Changing Image Modes?
在 Pillow 中,更改图像模式是指将图像从一种颜色表示法转换为另一种表示法。每种模式表示以图像中对颜色信息进行编码和解释的不同方式。
In Pillow changing image modes refers to the process of converting an image from one color representation to another. Each mode represents a different way of encoding and interpreting color information in an image.
更改图像模式出于多种用途很有用,例如针对特定应用(如打印、显示或分析)准备图像。它能让我们调整图像的颜色表示法以更好地满足我们的需求。
Changing image modes is useful for various purposes such as preparing images for specific applications like printing, display or analysis. It allows us to adapt the color representation of an image to better suit our needs.
在 Pillow 中,Image 类提供了一个名为 convert() 的方法,它允许我们更改图像的模式。图像的模式决定了它可以包含的像素值的类型和深度。
In Pillow the Image class provides a method called convert() that allows us to change the mode of an image. The mode of an image determines the type and depth of pixel values it can contain.
以下是 Image 类的 convert() 方法的语法和参数。
The following is the syntax and parameters of the convert() method of the Image class.
original_image.convert(mode)
其中,
Where,
-
original_image This is the source image whose mode we want to change.
-
mode This is a string specifying the desired mode for the new image.
以下是常见的更改图像模式。
The below are the common changing Image modes.
-
L − 8-bit pixels represent black and white
-
RGB − 3x8-bit pixels represent true color
-
RGBA − 4x8-bit pixels represent true color with transparency
-
CMYK − 4x8-bit pixels represent color separation
-
HSV − Hue, saturation, value color space
-
1 − 1-bit pixels, black and white which stored with one pixel per byte
以下是本章所有示例中使用的输入图像。
Following is the input image used in all the examples of this chapter.

Example
在此示例中,我们通过将模式参数 L 传递给 convert() 方法来将图像模式更改为黑白。
In this example we are changing the image mode into black and white by passing the mode argument as L to the convert() method.
from PIL import Image
#Open an image
original_image = Image.open("Images/rose.jpg")
#Convert the image to grayscale (mode 'L')
grayscale_image = original_image.convert("L")
#Save the resulting image
grayscale_image.save("output Image/output_grayscale.jpg")
grayscale_image.show()

Example
以下是在使用 convert() 方法将图像模式更改为 1 的另一个示例。
Here is the another example of changing the image mode to 1 by using the convert() method.
from PIL import Image
#Open an image
original_image = Image.open("Images/rose.jpg")
#Convert the image to RGBA mode
single_image = original_image.convert("1")
#Save the resulting image
single_image.save("output Image/output_single_image.jpg")
single_image.show()
