PIL-Pillow图像处理【1】-安装与新建

这篇博客介绍了PIL库的安装过程,包括正确的pip安装命令和错误示例。接着详细讲解了如何导入PIL库及其内部模块,并展示了PIL目录下的所有文件。此外,还探讨了如何使用PIL创建新图片,特别指出创建时的MODE、SIZE和COLOR参数。最后,讨论了图片格式转换的方法,包括转换的参数和用途。整个博客深入浅出地阐述了PIL库的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-----------对不起,目录似乎不好用---------改于2022.5.30 21时

目录

-1-Download安装

1.打开command(cmd)窗口

2.输入指令:

错误:

正确:

-2-import导入

-3-所有文件

-4-Create-创建一个新的图片。

-MODE-

-SIZE-

-COLOR-

-5-当你要改变图片格式【见上】时。

源码:

简介:

使用

 -6-当你想要打开图片


-1-Download安装

1.打开command(cmd)窗口

2.输入指令:

错误:

pip install PIL

结果:

ERROR: Could not find a version that satisfies the requirement PIL (from versions: none)
ERROR: No matching distribution found for PIL

---

正确:

pip install Pillow

-2-import导入

有意思的是,导入又需要输入:

import PIL

或者

from PIL import *

单个文件:

from PIL import ...

-3-所有文件

自己看!

|-PIL 		---<dir>
|	|-BdfFontFile.py 		---<file>
|	|-BlpImagePlugin.py 		---<file>
|	|-BmpImagePlugin.py 		---<file>
|	|-BufrStubImagePlugin.py 		---<file>
|	|-ContainerIO.py 		---<file>
|	|-CurImagePlugin.py 		---<file>
|	|-DcxImagePlugin.py 		---<file>
|	|-DdsImagePlugin.py 		---<file>
|	|-EpsImagePlugin.py 		---<file>
|	|-ExifTags.py 		---<file>
|	|-features.py 		---<file>
|	|-FitsStubImagePlugin.py 		---<file>
|	|-FliImagePlugin.py 		---<file>
|	|-FontFile.py 		---<file>
|	|-FpxImagePlugin.py 		---<file>
|	|-FtexImagePlugin.py 		---<file>
|	|-GbrImagePlugin.py 		---<file>
|	|-GdImageFile.py 		---<file>
|	|-GifImagePlugin.py 		---<file>
|	|-GimpGradientFile.py 		---<file>
|	|-GimpPaletteFile.py 		---<file>
|	|-GribStubImagePlugin.py 		---<file>
|	|-Hdf5StubImagePlugin.py 		---<file>
|	|-IcnsImagePlugin.py 		---<file>
|	|-IcoImagePlugin.py 		---<file>
|	|-Image.py 		---<file>
|	|-ImageChops.py 		---<file>
|	|-ImageCms.py 		---<file>
|	|-ImageColor.py 		---<file>
|	|-ImageDraw.py 		---<file>
|	|-ImageDraw2.py 		---<file>
|	|-ImageEnhance.py 		---<file>
|	|-ImageFile.py 		---<file>
|	|-ImageFilter.py 		---<file>
|	|-ImageFont.py 		---<file>
|	|-ImageGrab.py 		---<file>
|	|-ImageMath.py 		---<file>
|	|-ImageMode.py 		---<file>
|	|-ImageMorph.py 		---<file>
|	|-ImageOps.py 		---<file>
|	|-ImagePalette.py 		---<file>
|	|-ImagePath.py 		---<file>
|	|-ImageQt.py 		---<file>
|	|-ImageSequence.py 		---<file>
|	|-ImageShow.py 		---<file>
|	|-ImageStat.py 		---<file>
|	|-ImageTk.py 		---<file>
|	|-ImageTransform.py 		---<file>
|	|-ImageWin.py 		---<file>
|	|-ImImagePlugin.py 		---<file>
|	|-ImtImagePlugin.py 		---<file>
|	|-IptcImagePlugin.py 		---<file>
|	|-Jpeg2KImagePlugin.py 		---<file>
|	|-JpegImagePlugin.py 		---<file>
|	|-JpegPresets.py 		---<file>
|	|-McIdasImagePlugin.py 		---<file>
|	|-MicImagePlugin.py 		---<file>
|	|-MpegImagePlugin.py 		---<file>
|	|-MpoImagePlugin.py 		---<file>
|	|-MspImagePlugin.py 		---<file>
|	|-PaletteFile.py 		---<file>
|	|-PalmImagePlugin.py 		---<file>
|	|-PcdImagePlugin.py 		---<file>
|	|-PcfFontFile.py 		---<file>
|	|-PcxImagePlugin.py 		---<file>
|	|-PdfImagePlugin.py 		---<file>
|	|-PdfParser.py 		---<file>
|	|-PixarImagePlugin.py 		---<file>
|	|-PngImagePlugin.py 		---<file>
|	|-PpmImagePlugin.py 		---<file>
|	|-PsdImagePlugin.py 		---<file>
|	|-PSDraw.py 		---<file>
|	|-PyAccess.py 		---<file>
|	|-SgiImagePlugin.py 		---<file>
|	|-SpiderImagePlugin.py 		---<file>
|	|-SunImagePlugin.py 		---<file>
|	|-TarIO.py 		---<file>
|	|-TgaImagePlugin.py 		---<file>
|	|-TiffImagePlugin.py 		---<file>
|	|-TiffTags.py 		---<file>
|	|-WalImageFile.py 		---<file>
|	|-WebPImagePlugin.py 		---<file>
|	|-WmfImagePlugin.py 		---<file>
|	|-XbmImagePlugin.py 		---<file>
|	|-XpmImagePlugin.py 		---<file>
|	|-XVThumbImagePlugin.py 		---<file>
|	|-_binary.py 		---<file>
|	|-_imaging.cp39-win_amd64.pyd 		---<file>
|	|-_imagingcms.cp39-win_amd64.pyd 		---<file>
|	|-_imagingft.cp39-win_amd64.pyd 		---<file>
|	|-_imagingmath.cp39-win_amd64.pyd 		---<file>
|	|-_imagingmorph.cp39-win_amd64.pyd 		---<file>
|	|-_imagingtk.cp39-win_amd64.pyd 		---<file>
|	|-_tkinter_finder.py 		---<file>
|	|-_util.py 		---<file>
|	|-_version.py 		---<file>
|	|-_webp.cp39-win_amd64.pyd 		---<file>
|	|-__init__.py 		---<file>
|	|-__main__.py 		---<file>
|	|-__pycache__ 		---<dir>
|	|	|-BdfFontFile.cpython-39.pyc 		---<file>
|	|	|-BlpImagePlugin.cpython-39.pyc 		---<file>
|	|	|-BmpImagePlugin.cpython-39.pyc 		---<file>
|	|	|-BufrStubImagePlugin.cpython-39.pyc 		---<file>
|	|	|-ContainerIO.cpython-39.pyc 		---<file>
|	|	|-CurImagePlugin.cpython-39.pyc 		---<file>
|	|	|-DcxImagePlugin.cpython-39.pyc 		---<file>
|	|	|-DdsImagePlugin.cpython-39.pyc 		---<file>
|	|	|-EpsImagePlugin.cpython-39.pyc 		---<file>
|	|	|-ExifTags.cpython-39.pyc 		---<file>
|	|	|-features.cpython-39.pyc 		---<file>
|	|	|-FitsStubImagePlugin.cpython-39.pyc 		---<file>
|	|	|-FliImagePlugin.cpython-39.pyc 		---<file>
|	|	|-FontFile.cpython-39.pyc 		---<file>
|	|	|-FpxImagePlugin.cpython-39.pyc 		---<file>
|	|	|-FtexImagePlugin.cpython-39.pyc 		---<file>
|	|	|-GbrImagePlugin.cpython-39.pyc 		---<file>
|	|	|-GdImageFile.cpython-39.pyc 		---<file>
|	|	|-GifImagePlugin.cpython-39.pyc 		---<file>
|	|	|-GimpGradientFile.cpython-39.pyc 		---<file>
|	|	|-GimpPaletteFile.cpython-39.pyc 		---<file>
|	|	|-GribStubImagePlugin.cpython-39.pyc 		---<file>
|	|	|-Hdf5StubImagePlugin.cpython-39.pyc 		---<file>
|	|	|-IcnsImagePlugin.cpython-39.pyc 		---<file>
|	|	|-IcoImagePlugin.cpython-39.pyc 		---<file>
|	|	|-Image.cpython-39.pyc 		---<file>
|	|	|-ImageChops.cpython-39.pyc 		---<file>
|	|	|-ImageCms.cpython-39.pyc 		---<file>
|	|	|-ImageColor.cpython-39.pyc 		---<file>
|	|	|-ImageDraw.cpython-39.pyc 		---<file>
|	|	|-ImageDraw2.cpython-39.pyc 		---<file>
|	|	|-ImageEnhance.cpython-39.pyc 		---<file>
|	|	|-ImageFile.cpython-39.pyc 		---<file>
|	|	|-ImageFilter.cpython-39.pyc 		---<file>
|	|	|-ImageFont.cpython-39.pyc 		---<file>
|	|	|-ImageGrab.cpython-39.pyc 		---<file>
|	|	|-ImageMath.cpython-39.pyc 		---<file>
|	|	|-ImageMode.cpython-39.pyc 		---<file>
|	|	|-ImageMorph.cpython-39.pyc 		---<file>
|	|	|-ImageOps.cpython-39.pyc 		---<file>
|	|	|-ImagePalette.cpython-39.pyc 		---<file>
|	|	|-ImagePath.cpython-39.pyc 		---<file>
|	|	|-ImageQt.cpython-39.pyc 		---<file>
|	|	|-ImageSequence.cpython-39.pyc 		---<file>
|	|	|-ImageShow.cpython-39.pyc 		---<file>
|	|	|-ImageStat.cpython-39.pyc 		---<file>
|	|	|-ImageTk.cpython-39.pyc 		---<file>
|	|	|-ImageTransform.cpython-39.pyc 		---<file>
|	|	|-ImageWin.cpython-39.pyc 		---<file>
|	|	|-ImImagePlugin.cpython-39.pyc 		---<file>
|	|	|-ImtImagePlugin.cpython-39.pyc 		---<file>
|	|	|-IptcImagePlugin.cpython-39.pyc 		---<file>
|	|	|-Jpeg2KImagePlugin.cpython-39.pyc 		---<file>
|	|	|-JpegImagePlugin.cpython-39.pyc 		---<file>
|	|	|-JpegPresets.cpython-39.pyc 		---<file>
|	|	|-McIdasImagePlugin.cpython-39.pyc 		---<file>
|	|	|-MicImagePlugin.cpython-39.pyc 		---<file>
|	|	|-MpegImagePlugin.cpython-39.pyc 		---<file>
|	|	|-MpoImagePlugin.cpython-39.pyc 		---<file>
|	|	|-MspImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PaletteFile.cpython-39.pyc 		---<file>
|	|	|-PalmImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PcdImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PcfFontFile.cpython-39.pyc 		---<file>
|	|	|-PcxImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PdfImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PdfParser.cpython-39.pyc 		---<file>
|	|	|-PixarImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PngImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PpmImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PsdImagePlugin.cpython-39.pyc 		---<file>
|	|	|-PSDraw.cpython-39.pyc 		---<file>
|	|	|-PyAccess.cpython-39.pyc 		---<file>
|	|	|-SgiImagePlugin.cpython-39.pyc 		---<file>
|	|	|-SpiderImagePlugin.cpython-39.pyc 		---<file>
|	|	|-SunImagePlugin.cpython-39.pyc 		---<file>
|	|	|-TarIO.cpython-39.pyc 		---<file>
|	|	|-TgaImagePlugin.cpython-39.pyc 		---<file>
|	|	|-TiffImagePlugin.cpython-39.pyc 		---<file>
|	|	|-TiffTags.cpython-39.pyc 		---<file>
|	|	|-WalImageFile.cpython-39.pyc 		---<file>
|	|	|-WebPImagePlugin.cpython-39.pyc 		---<file>
|	|	|-WmfImagePlugin.cpython-39.pyc 		---<file>
|	|	|-XbmImagePlugin.cpython-39.pyc 		---<file>
|	|	|-XpmImagePlugin.cpython-39.pyc 		---<file>
|	|	|-XVThumbImagePlugin.cpython-39.pyc 		---<file>
|	|	|-_binary.cpython-39.pyc 		---<file>
|	|	|-_tkinter_finder.cpython-39.pyc 		---<file>
|	|	|-_util.cpython-39.pyc 		---<file>
|	|	|-_version.cpython-39.pyc 		---<file>
|	|	|-__init__.cpython-39.pyc 		---<file>
|	|	|-__main__.cpython-39.pyc 		---<file>

-4-Create-创建一个新的图片。

注意:

相信在第三节中你也发现了,PIL只是一个文件夹,引用它就相当于是引用了PIL目录下的__init__.py,故输入 import PIL是不行的。

---------

创建图片的方法:Image.new

目录

-MODE-

-SIZE-

-COLOR-


1】from PIL import Image

首先就需要把要用的Image库导入。

2】img=Image.new(MODE,SIZE,COLOR)

再看一下官方说明【源码】:

def new(mode, size, color=0):
    """
    Creates a new image with the given mode and size.

    :param mode: The mode to use for the new image. See:
       :ref:`concept-modes`.
    :param size: A 2-tuple, containing (width, height) in pixels.
    :param color: What color to use for the image.  Default is black.
       If given, this should be a single integer or floating point value
       for single-band modes, and a tuple for multi-band modes (one value
       per band).  When creating RGB images, you can also use color
       strings as supported by the ImageColor module.  If the color is
       None, the image is not initialised.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    _check_size(size)

    if color is None:
        # don't initialize
        return Image()._new(core.new(mode, size))

    if isinstance(color, str):
        # css3-style specifier

        from . import ImageColor

        color = ImageColor.getcolor(color, mode)

    im = Image()
    if mode == "P" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:
        # RGB or RGBA value for a P image
        from . import ImagePalette

        im.palette = ImagePalette.ImagePalette()
        color = im.palette.getcolor(color)
    return im._new(core.fill(mode, size, color))

--------------------------------------------------------------------------------------------

-MODE-

 解析:                         |___MODE:模式。有RGB(三色组合,一般为.jpg),

                                                RGBA(多了透明度,存储为.png格式),

                                                1[位图(.bmp),像素1位],

                                                L[灰度,像素8位],

                                                I[像素Int32],

                                                F[像素Float32],

                                                 P(PA)[8位,映射图片]______

                                                CMYK[印刷]                             |

                                                YCbCr[亮色分离]                     |

                                                                                                |

                               关于图像的映射(P形式),看一下:【Python】PIL库中图像的mode参数_mjiansun的博客-优快云博客

-SIZE-

要求:tuple数组。否则:

ValueError: Size must be a tuple

例:(90,100)

表示上面长90像素,高100像素。

-COLOR-

实际上:

Image.new( mode, size ) => image
Image.new( mode, size, color ) => image

color作为附加的一个参数,表示填充颜色,不填则默认为黑。

程序例子:

from PIL import Image
img=Image.new("RGB",(100,100),"red")
img.show()

 

水印是自动添加的,电脑上没有 

-5-当你要改变图片格式【见上】时。

图片格式:见-MODE

newimg=Image.convert(mode=None, matrix=None, dither=None, palette=WEB, colors=256)

源码:

def convert(self, mode=None, matrix=None, dither=None, palette=WEB, colors=256):
    """
    Returns a converted copy of this image. For the "P" mode, this
    method translates pixels through the palette.  If mode is
    omitted, a mode is chosen so that all information in the image
    and the palette can be represented without a palette.

    The current version supports all possible conversions between
    "L", "RGB" and "CMYK." The ``matrix`` argument only supports "L"
    and "RGB".

    When translating a color image to greyscale (mode "L"),
    the library uses the ITU-R 601-2 luma transform::

        L = R * 299/1000 + G * 587/1000 + B * 114/1000

    The default method of converting a greyscale ("L") or "RGB"
    image into a bilevel (mode "1") image uses Floyd-Steinberg
    dither to approximate the original image luminosity levels. If
    dither is :data:`NONE`, all values larger than 128 are set to 255 (white),
    all other values to 0 (black). To use other thresholds, use the
    :py:meth:`~PIL.Image.Image.point` method.

    When converting from "RGBA" to "P" without a ``matrix`` argument,
    this passes the operation to :py:meth:`~PIL.Image.Image.quantize`,
    and ``dither`` and ``palette`` are ignored.

    :param mode: The requested mode. See: :ref:`concept-modes`.
    :param matrix: An optional conversion matrix.  If given, this
       should be 4- or 12-tuple containing floating point values.
    :param dither: Dithering method, used when converting from
       mode "RGB" to "P" or from "RGB" or "L" to "1".
       Available methods are :data:`NONE` or :data:`FLOYDSTEINBERG` (default).
       Note that this is not used when ``matrix`` is supplied.
    :param palette: Palette to use when converting from mode "RGB"
       to "P".  Available palettes are :data:`WEB` or :data:`ADAPTIVE`.
    :param colors: Number of colors to use for the :data:`ADAPTIVE` palette.
       Defaults to 256.
    :rtype: :py:class:`~PIL.Image.Image`
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    self.load()

    if not mode and self.mode == "P":
        # determine default mode
        if self.palette:
            mode = self.palette.mode
        else:
            mode = "RGB"
    if not mode or (mode == self.mode and not matrix):
        return self.copy()

    has_transparency = self.info.get("transparency") is not None
    if matrix:
        # matrix conversion
        if mode not in ("L", "RGB"):
            raise ValueError("illegal conversion")
        im = self.im.convert_matrix(mode, matrix)
        new = self._new(im)
        if has_transparency and self.im.bands == 3:
            transparency = new.info["transparency"]

            def convert_transparency(m, v):
                v = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3] * 0.5
                return max(0, min(255, int(v)))

            if mode == "L":
                transparency = convert_transparency(matrix, transparency)
            elif len(mode) == 3:
                transparency = tuple(
                    [
                        convert_transparency(
                            matrix[i * 4 : i * 4 + 4], transparency
                        )
                        for i in range(0, len(transparency))
                    ]
                )
            new.info["transparency"] = transparency
        return new

    if mode == "P" and self.mode == "RGBA":
        return self.quantize(colors)

    trns = None
    delete_trns = False
    # transparency handling
    if has_transparency:
        if self.mode in ("1", "L", "I", "RGB") and mode == "RGBA":
            # Use transparent conversion to promote from transparent
            # color to an alpha channel.
            new_im = self._new(
                self.im.convert_transparent(mode, self.info["transparency"])
            )
            del new_im.info["transparency"]
            return new_im
        elif self.mode in ("L", "RGB", "P") and mode in ("L", "RGB", "P"):
            t = self.info["transparency"]
            if isinstance(t, bytes):
                # Dragons. This can't be represented by a single color
                warnings.warn(
                    "Palette images with Transparency expressed in bytes should be "
                    "converted to RGBA images"
                )
                delete_trns = True
            else:
                # get the new transparency color.
                # use existing conversions
                trns_im = Image()._new(core.new(self.mode, (1, 1)))
                if self.mode == "P":
                    trns_im.putpalette(self.palette)
                    if isinstance(t, tuple):
                        try:
                            t = trns_im.palette.getcolor(t)
                        except Exception as e:
                            raise ValueError(
                                "Couldn't allocate a palette color for transparency"
                            ) from e
                trns_im.putpixel((0, 0), t)

                if mode in ("L", "RGB"):
                    trns_im = trns_im.convert(mode)
                else:
                    # can't just retrieve the palette number, got to do it
                    # after quantization.
                    trns_im = trns_im.convert("RGB")
                trns = trns_im.getpixel((0, 0))

        elif self.mode == "P" and mode == "RGBA":
            t = self.info["transparency"]
            delete_trns = True

            if isinstance(t, bytes):
                self.im.putpalettealphas(t)
            elif isinstance(t, int):
                self.im.putpalettealpha(t, 0)
            else:
                raise ValueError("Transparency for P mode should be bytes or int")

    if mode == "P" and palette == ADAPTIVE:
        im = self.im.quantize(colors)
        new = self._new(im)
        from . import ImagePalette

        new.palette = ImagePalette.raw("RGB", new.im.getpalette("RGB"))
        if delete_trns:
            # This could possibly happen if we requantize to fewer colors.
            # The transparency would be totally off in that case.
            del new.info["transparency"]
        if trns is not None:
            try:
                new.info["transparency"] = new.palette.getcolor(trns)
            except Exception:
                # if we can't make a transparent color, don't leave the old
                # transparency hanging around to mess us up.
                del new.info["transparency"]
                warnings.warn("Couldn't allocate palette entry for transparency")
        return new

    # colorspace conversion
    if dither is None:
        dither = FLOYDSTEINBERG

    try:
        im = self.im.convert(mode, dither)
    except ValueError:
        try:
            # normalize source image and try again
            im = self.im.convert(getmodebase(self.mode))
            im = im.convert(mode, dither)
        except KeyError as e:
            raise ValueError("illegal conversion") from e

    new_im = self._new(im)
    if delete_trns:
        # crash fail if we leave a bytes transparency in an rgb/l mode.
        del new_im.info["transparency"]
    if trns is not None:
        if new_im.mode == "P":
            try:
                new_im.info["transparency"] = new_im.palette.getcolor(trns)
            except Exception:
                del new_im.info["transparency"]
                warnings.warn("Couldn't allocate palette entry for transparency")
        else:
            new_im.info["transparency"] = trns
    return new_im

简介:

(机译-翻译自源码-简介)

返回此图像的转换副本。对于“P”模式,这
    方法通过调色板转换像素。如果模式是
    省略,选择一种模式,以便图像中的所有信息
    并且调色板可以在没有调色板的情况下表示。

    当前版本支持所有可能的转换
    “L”、“RGB”和“CMYK”。 ``matrix`` 参数只支持“L”
    和“RGB”。

    将彩色图像转换为灰度(模式“L”)时,
    该库使用 ITU-R 601-2 亮度变换::

        L = R * 299/1000 + G * 587/1000 + B * 114/1000

    转换灰度(“L”)或“RGB”的默认方法
    将图像转换为双层(模式“1”)图像使用 Floyd-Steinberg
    抖动以近似原始图像亮度级别。如果
    抖动是:data:`NONE`,所有大于 128 的值都设置为 255(白色),
    所有其他值都为 0(黑色)。要使用其他阈值,请使用
    :py:meth:`~PIL.Image.Image.point` 方法。

    在没有“矩阵”参数的情况下从“RGBA”转换为“P”时,
    这会将操作传递给:py:meth:`~PIL.Image.Image.quantize`,
    和 ``dither`` 和 ``palette`` 被忽略。

    :param mode:请求的模式。参见::ref:`concept-modes`。
    :param 矩阵:可选的转换矩阵。如果给出,这
       应该是包含浮点值的 4 或 12 元组。
    :param dither: 抖动方法,从转换时使用
       模式“RGB”到“P”或从“RGB”或“L”到“1”。
       可用的方法是:data:`NONE` 或:data:`FLOYDSTEINBERG`(默认)。
       请注意,在提供 ``matrix`` 时不使用它。
    :param palette: 从模式“RGB”转换时使用的调色板
       最佳”。可用的调色板是 :data:`WEB` 或 :data:`ADAPTIVE`。
    :param 颜色:用于 :data:`ADAPTIVE` 调色板的颜色数。
       默认为 256。
    :rtype: :py:class:`~PIL.Image.Image`
    :returns: 一个:py:class:`~PIL.Image.Image` 对象。

----------------

使用

不要害怕,不要被它吓到。

一般来说,当你打开了一个图片【在程序里】,你可能要转换一下格式以便于操作。

#img是打开的图片变量。
newimg=img.convert("RGBA")
#当然,只要是之前提到的类型都可以,这里只是一个例子。

简介中还提到,把RGB格式转换为L->

L = R * 299/1000 + G * 587/1000+ B * 114/1000 是RGB转为L的公式。 

 一般来讲,这些就够了。

如果你想了解更多。。。

没有更多了!【手动无语】

可能你只能慢慢在国外官网里找了。。。PILhttp://pythonware.com/products/pil/

 -6-当你想要打开图片

Image.open(path)

def open(fp, mode="r", formats=None):
    """
    Opens and identifies the given image file.

    This is a lazy operation; this function identifies the file, but
    the file remains open and the actual image data is not read from
    the file until you try to process the data (or call the
    :py:meth:`~PIL.Image.Image.load` method).  See
    :py:func:`~PIL.Image.new`. See :ref:`file-handling`.

    :param fp: A filename (string), pathlib.Path object or a file object.
       The file object must implement ``file.read``,
       ``file.seek``, and ``file.tell`` methods,
       and be opened in binary mode.
    :param mode: The mode.  If given, this argument must be "r".
    :param formats: A list or tuple of formats to attempt to load the file in.
       This can be used to restrict the set of formats checked.
       Pass ``None`` to try all supported formats. You can print the set of
       available formats by running ``python -m PIL`` or using
       the :py:func:`PIL.features.pilinfo` function.
    :returns: An :py:class:`~PIL.Image.Image` object.
    :exception FileNotFoundError: If the file cannot be found.
    :exception PIL.UnidentifiedImageError: If the image cannot be opened and
       identified.
    :exception ValueError: If the ``mode`` is not "r", or if a ``StringIO``
       instance is used for ``fp``.
    :exception TypeError: If ``formats`` is not ``None``, a list or a tuple.
    """

同样,也不要被吓到!!!


a=Image.open(路径)

表示加载一个图片,接下来就可以操作了!

_________________________________

Image.open()其实相当于只打开了一个前缀,要完整加载要等到真实操作的时候。

Image.load()可以强制加载。 

<think>好的,用户想用Pillow库实现图像的透明或半透明效果。首先,我得回忆一下Pillow的相关知识。记得处理透明主要和Alpha通道有关,RGBA模式支持透明度。可能需要将图像转换为RGBA模式,然后调整Alpha值。 用户的问题可能涉及两个方面:一是将整个图像设置为透明,比如调整整体透明度;二是对特定区域进行透明处理,比如去除背景。根据提供的引用,引用[4]提到创建半透明图像时用了Image.new("RGBA", ...),并设置了color中的Alpha值。这可能是一个方法。 另外,保存图像时要注意格式支持透明度,比如PNG支持,而JPEG不支持。引用[4]中的例子保存为BMP,但BMP可能不支持透明度,可能需要用PNG格式。 对于整体透明度,可能需要遍历每个像素,修改Alpha通道的值。或者使用带Alpha通道的颜色填充。例如,使用Image.blend或者合成图像。引用[3]提到rotate方法,但可能不直接相关。 步骤可能包括:打开图像,转换为RGBA模式,处理Alpha通道,保存为支持透明的格式。如果是设置整体半透明,可以创建一个新的Alpha层,或者修改每个像素的Alpha值。或者用Image.new创建带有透明度的图像,然后粘贴原图。 还要注意,如果原图没有Alpha通道,转换到RGBA后才能处理。引用[4]中的例子也展示了如何打开图像并保存为不同格式,但需要确保模式正确。 可能需要用到putalpha()方法,或者使用像素访问方式修改每个像素的Alpha值。例如,split()获取各个通道,然后合并新的Alpha通道。 可能遇到的问题包括:图像模式不正确,保存格式不支持透明,或者处理后的效果不符合预期。需要确保每一步都正确转换和保存。 总结步骤:打开图像,转换模式为RGBA,调整Alpha值,保存为PNG。如果是半透明,可以新建一个原图同尺寸的Alpha层,数值为半透明值,然后合并。或者直接修改每个像素的Alpha值,比如乘以一个系数。 现在需要将这些步骤转化为具体的Python代码,使用Pillow库的函数。例如,使用Image.convert('RGBA'),然后操作像素数据。或者使用Image.new创建带透明度的图层,再原图合成。</think>### 分步实现图像透明/半透明效果的方法 #### 1. 基础操作:为图像添加全局透明度 ```python from PIL import Image # 打开图像并转换为RGBA模式(支持透明度) im = Image.open("input.jpg").convert("RGBA") # 创建新的Alpha通道(0-255,0为全透明) alpha = im.split()[3] # 获取原始Alpha通道 new_alpha = alpha.point(lambda x: int(x * 0.5)) # 设置50%透明度 # 合并新Alpha通道 im.putalpha(new_alpha) im.save("output.png") # 必须保存为支持透明的格式(如PNG) ``` 关键点: - 必须转换到$RGBA$颜色模式[^4] - Alpha值范围$0 \le \alpha \le 255$(0为全透明) - 保存格式需支持透明度(推荐PNG) #### 2. 创建半透明色块覆盖 ```python # 创建半透明覆盖层(图像同尺寸) overlay = Image.new("RGBA", im.size, (255, 0, 0, 128)) # 半透明红色 # 合成图像 combined = Image.alpha_composite(im, overlay) combined.save("overlay.png") ``` 公式说明: $$ \text{合成颜色} = \alpha_{\text{overlay}} \cdot C_{\text{overlay}} + (1 - \alpha_{\text{overlay}}) \cdot C_{\text{base}} $$ 其中$C$表示颜色分量,$\alpha$为透明度值 #### 3. 高级应用:渐变透明度效果 ```python # 创建垂直渐变Alpha通道(0-255) width, height = im.size gradient = Image.new("L", (width, height)) for y in range(height): alpha_value = int(255 * y/height) gradient.putpixel((0, y), alpha_value) gradient.paste(alpha_value, (0, y, width, y+1)) im.putalpha(gradient) im.save("gradient_trans.png") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Unconquerable p

给点吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值