Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
Pillow (PIL Fork) 12.0.0 documentation
Light LogoDark Logo
Pillow (PIL Fork) 12.0.0 documentation
Back to top

Image module

TheImage module provides a class with the same name which isused to represent a PIL image. The module also provides a number of factoryfunctions, including functions to load images from files, and to create newimages.

Examples

Open, rotate, and display an image (using the default viewer)

The following script loads an image, rotates it 45 degrees, and displays itusing an external viewer (usually xv on Unix, and the Paint program onWindows).

fromPILimportImagewithImage.open("hopper.jpg")asim:im.rotate(45).show()

Create thumbnails

The following script creates nice thumbnails of all JPEG images in thecurrent directory preserving aspect ratios with 128x128 max resolution.

fromPILimportImageimportglob,ossize=128,128forinfileinglob.glob("*.jpg"):file,ext=os.path.splitext(infile)withImage.open(infile)asim:im.thumbnail(size)im.save(file+".thumbnail","JPEG")

Functions

PIL.Image.open(fp:StrOrBytesPath|IO[bytes],mode:Literal['r']='r',formats:list[str]|tuple[str,...]|None=None)ImageFile.ImageFile[source]

Opens and identifies the given image file.

This is a lazy operation; this function identifies the file, butthe file remains open and the actual image data is not read fromthe file until you try to process the data (or call theload() method). Seenew(). SeeFile handling in Pillow.

Parameters:
  • fp – A filename (string), os.PathLike object or a file object.The file object must implementfile.read,file.seek, andfile.tell methods,and be opened in binary mode. The file object will also seek to zerobefore reading.

  • mode – The mode. If given, this argument must be “r”.

  • 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.PassNone to try all supported formats. You can print the set ofavailable formats by runningpython3-mPIL or usingthePIL.features.pilinfo() function.

Returns:

AnImage object.

Raises:

Warning

To protect against potential DOS attacks caused by “decompression bombs” (i.e. malicious fileswhich decompress into a huge amount of data and are designed to crash or cause disruption by using upa lot of memory), Pillow will issue aDecompressionBombWarning if the number of pixels in animage is over a certain limit,MAX_IMAGE_PIXELS.

This threshold can be changed by settingMAX_IMAGE_PIXELS. It can be disabledby settingImage.MAX_IMAGE_PIXELS=None.

If desired, the warning can be turned into an error withwarnings.simplefilter('error',Image.DecompressionBombWarning) or suppressed entirely withwarnings.simplefilter('ignore',Image.DecompressionBombWarning). See alsothe logging documentation to have warnings output to the logging facility instead of stderr.

If the number of pixels is greater than twiceMAX_IMAGE_PIXELS, then aDecompressionBombError will be raised instead.

Image processing

PIL.Image.alpha_composite(im1:Image,im2:Image)Image[source]

Alpha composite im2 over im1.

Parameters:
  • im1 – The first image. Must have mode RGBA or LA.

  • im2 – The second image. Must have the same mode and size as the first image.

Returns:

AnImage object.

PIL.Image.blend(im1:Image,im2:Image,alpha:float)Image[source]

Creates a new image by interpolating between two input images, usinga constant alpha:

out=image1*(1.0-alpha)+image2*alpha
Parameters:
  • im1 – The first image.

  • im2 – The second image. Must have the same mode and size asthe first image.

  • alpha – The interpolation alpha factor. If alpha is 0.0, acopy of the first image is returned. If alpha is 1.0, a copy ofthe second image is returned. There are no restrictions on thealpha value. If necessary, the result is clipped to fit intothe allowed output range.

Returns:

AnImage object.

PIL.Image.composite(image1:Image,image2:Image,mask:Image)Image[source]

Create composite image by blending images using a transparency mask.

Parameters:
  • image1 – The first image.

  • image2 – The second image. Must have the same mode andsize as the first image.

  • mask – A mask image. This image can have mode“1”, “L”, or “RGBA”, and must have the same size as theother two images.

PIL.Image.eval(image:Image,*args:Callable[[int],float])Image[source]

Applies the function (which should take one argument) to each pixelin the given image. If the image has more than one band, the samefunction is applied to each band. Note that the function isevaluated once for each possible pixel value, so you cannot userandom components or other generators.

Parameters:
  • image – The input image.

  • function – A function object, taking one integer argument.

Returns:

AnImage object.

PIL.Image.merge(mode:str,bands:Sequence[Image])Image[source]

Merge a set of single band images into a new multiband image.

Parameters:
  • mode – The mode to use for the output image. See:Modes.

  • bands – A sequence containing one single-band image foreach band in the output image. All bands must have thesame size.

Returns:

AnImage object.

Constructing images

PIL.Image.new(mode:str,size:tuple[int,int]|list[int],color:float|tuple[float,...]|str|None=0)Image[source]

Creates a new image with the given mode and size.

Parameters:
  • mode – The mode to use for the new image. See:Modes.

  • size – A 2-tuple, containing (width, height) in pixels.

  • 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-bandmodes, and a tuple for multi-band modes (one value per band). Whencreating RGB or HSV images, you can also use color strings as supportedby the ImageColor module. SeeColors for more information. If thecolor is None, the image is not initialised.

Returns:

AnImage object.

PIL.Image.fromarray(obj:SupportsArrayInterface,mode:str|None=None)Image[source]

Creates an image memory from an object exporting the array interface(using the buffer protocol):

fromPILimportImageimportnumpyasnpa=np.zeros((5,5))im=Image.fromarray(a)

Ifobj is not contiguous, then thetobytes method is calledandfrombuffer() is used.

In the case of NumPy, be aware that Pillow modes do not always correspondto NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,32-bit signed integer pixels, and 32-bit floating point pixels.

Pillow images can also be converted to arrays:

fromPILimportImageimportnumpyasnpim=Image.open("hopper.jpg")a=np.asarray(im)

When converting Pillow images to arrays however, only pixel values aretransferred. This means that P and PA mode images will lose their palette.

Parameters:
  • obj – Object with array interface

  • mode

    Optional mode to use when readingobj. Since pixel values do notcontain information about palettes or color spaces, this can be used to placegrayscale L mode data within a P mode image, or read RGB data as YCbCr forexample.

    See:Modes for general information about modes.

Returns:

An image object.

Added in version 1.1.6.

PIL.Image.fromarrow(obj:SupportsArrowArrayInterface,mode:str,size:tuple[int,int])Image[source]

Creates an image with zero-copy shared memory from an object exportingthe arrow_c_array interface protocol:

fromPILimportImageimportpyarrowaspaarr=pa.array([0]*(5*5*4),type=pa.uint8())im=Image.fromarrow(arr,'RGBA',(5,5))

If the data representation of theobj is not compatible withPillow internal storage, a ValueError is raised.

Pillow images can also be converted to Arrow objects:

fromPILimportImageimportpyarrowaspaim=Image.open('hopper.jpg')arr=pa.array(im)

As with array support, when converting Pillow images to arrays,only pixel values are transferred. This means that P and PA modeimages will lose their palette.

Parameters:
  • obj – Object with an arrow_c_array interface

  • mode – Image mode.

  • size – Image size. This must match the storage of the arrow object.

Returns:

An Image object

Note that according to the Arrow spec, both the producer and theconsumer should consider the exported array to be immutable, asunsynchronized updates will potentially cause inconsistent data.

See:Arrow support for more detailed information

Added in version 11.2.1.

PIL.Image.frombytes(mode:str,size:tuple[int,int],data:bytes|bytearray|SupportsArrayInterface,decoder_name:str='raw',*args:Any)Image[source]

Creates a copy of an image memory from pixel data in a buffer.

In its simplest form, this function takes three arguments(mode, size, and unpacked pixel data).

You can also use any pixel decoder supported by PIL. For moreinformation on available decoders, see the sectionWriting Your Own File Codec.

Note that this function decodes pixel data only, not entire images.If you have an entire image in a string, wrap it in aBytesIO object, and useopen() to loadit.

Parameters:
  • mode – The image mode. See:Modes.

  • size – The image size.

  • data – A byte buffer containing raw data for the given mode.

  • decoder_name – What decoder to use.

  • args – Additional parameters for the given decoder.

Returns:

AnImage object.

PIL.Image.frombuffer(mode:str,size:tuple[int,int],data:bytes|SupportsArrayInterface,decoder_name:str='raw',*args:Any)Image[source]

Creates an image memory referencing pixel data in a byte buffer.

This function is similar tofrombytes(), but uses datain the byte buffer, where possible. This means that changes to theoriginal buffer object are reflected in this image). Not all modes canshare memory; supported modes include “L”, “RGBX”, “RGBA”, and “CMYK”.

Note that this function decodes pixel data only, not entire images.If you have an entire image file in a string, wrap it in aBytesIO object, and useopen() to load it.

The default parameters used for the “raw” decoder differs from that used forfrombytes(). This is a bug, and will probably be fixed in afuture release. The current release issues a warning if you do this; to disablethe warning, you should provide the full set of parameters. See below for details.

Parameters:
  • mode – The image mode. See:Modes.

  • size – The image size.

  • data – A bytes or other buffer object containing rawdata for the given mode.

  • decoder_name – What decoder to use.

  • args

    Additional parameters for the given decoder. For thedefault encoder (“raw”), it’s recommended that you provide thefull set of parameters:

    frombuffer(mode,size,data,"raw",mode,0,1)

Returns:

AnImage object.

Added in version 1.1.4.

Generating images

PIL.Image.effect_mandelbrot(size:tuple[int,int],extent:tuple[float,float,float,float],quality:int)Image[source]

Generate a Mandelbrot set covering the given extent.

Parameters:
  • size – The requested size in pixels, as a 2-tuple:(width, height).

  • extent – The extent to cover, as a 4-tuple:(x0, y0, x1, y1).

  • quality – Quality.

PIL.Image.effect_noise(size:tuple[int,int],sigma:float)Image[source]

Generate Gaussian noise centered around 128.

Parameters:
  • size – The requested size in pixels, as a 2-tuple:(width, height).

  • sigma – Standard deviation of noise.

PIL.Image.linear_gradient(mode:str)Image[source]

Generate 256x256 linear gradient from black to white, top to bottom.

Parameters:

mode – Input mode.

PIL.Image.radial_gradient(mode:str)Image[source]

Generate 256x256 radial gradient from black to white, centre to edge.

Parameters:

mode – Input mode.

Registering plugins

PIL.Image.preinit()None[source]

Explicitly loads BMP, GIF, JPEG, PPM and PPM file format drivers.

It is called when opening or saving images.

PIL.Image.init()bool[source]

Explicitly initializes the Python Imaging Library. This functionloads all available file format drivers.

It is called when opening or saving images ifpreinit() isinsufficient, and bypilinfo().

Note

These functions are for use by plugin authors. They are called when aplugin is loaded as part ofpreinit() orinit().Application authors can ignore them.

PIL.Image.register_open(id:str,factory:Callable[[IO[bytes],str|bytes],ImageFile.ImageFile]|type[ImageFile.ImageFile],accept:Callable[[bytes],bool|str]|None=None)None[source]

Register an image file plugin. This function should not be usedin application code.

Parameters:
  • id – An image format identifier.

  • factory – An image file factory method.

  • accept – An optional function that can be used to quicklyreject images having another format.

PIL.Image.register_mime(id:str,mimetype:str)None[source]

Registers an image MIME type by populatingImage.MIME. This functionshould not be used in application code.

Image.MIME provides a mapping from image format identifiers to mimeformats, butget_format_mimetype() canprovide a different result for specific images.

Parameters:
  • id – An image format identifier.

  • mimetype – The image MIME type for this format.

PIL.Image.register_save(id:str,driver:Callable[[Image,IO[bytes],str|bytes],None])None[source]

Registers an image save function. This function should not beused in application code.

Parameters:
  • id – An image format identifier.

  • driver – A function to save images in this format.

PIL.Image.register_save_all(id:str,driver:Callable[[Image,IO[bytes],str|bytes],None])None[source]

Registers an image function to save all the framesof a multiframe format. This function should not beused in application code.

Parameters:
  • id – An image format identifier.

  • driver – A function to save images in this format.

PIL.Image.register_extension(id:str,extension:str)None[source]

Registers an image extension. This function should not beused in application code.

Parameters:
  • id – An image format identifier.

  • extension – An extension used for this format.

PIL.Image.register_extensions(id:str,extensions:list[str])None[source]

Registers image extensions. This function should not beused in application code.

Parameters:
  • id – An image format identifier.

  • extensions – A list of extensions used for this format.

PIL.Image.registered_extensions()dict[str,str][source]

Returns a dictionary containing all file extensions belongingto registered plugins

PIL.Image.register_decoder(name:str,decoder:type[ImageFile.PyDecoder])None[source]

Registers an image decoder. This function should not beused in application code.

Parameters:
  • name – The name of the decoder

  • decoder – An ImageFile.PyDecoder object

Added in version 4.1.0.

PIL.Image.register_encoder(name:str,encoder:type[ImageFile.PyEncoder])None[source]

Registers an image encoder. This function should not beused in application code.

Parameters:
  • name – The name of the encoder

  • encoder – An ImageFile.PyEncoder object

Added in version 4.1.0.

The Image class

classPIL.Image.Image[source]

This class represents an image object. To createImage objects, use the appropriate factoryfunctions. There’s hardly ever any reason to call the Image constructordirectly.

An instance of theImage class has the followingmethods. Unless otherwise stated, all methods return a new instance of theImage class, holding the resulting image.

Image.alpha_composite(im:Image,dest:Sequence[int]=(0,0),source:Sequence[int]=(0,0))None[source]

‘In-place’ analog of Image.alpha_composite. Composites an imageonto this image.

Parameters:
  • im – image to composite over this one

  • dest – Optional 2 tuple (left, top) specifying the upperleft corner in this (destination) image.

  • source – Optional 2 (left, top) tuple for the upper leftcorner in the overlay source image, or 4 tuple (left, top, right,bottom) for the bounds of the source rectangle

Performance Note: Not currently implemented in-place in the core layer.

Image.apply_transparency()None[source]

If a P mode image has a “transparency” key in the info dictionary,remove the key and instead apply the transparency to the palette.Otherwise, the image is unchanged.

Image.convert(mode:str|None=None,matrix:tuple[float,...]|None=None,dither:Dither|None=None,palette:Palette=Palette.WEB,colors:int=256)Image[source]

Returns a converted copy of this image. For the “P” mode, thismethod translates pixels through the palette. If mode isomitted, a mode is chosen so that all information in the imageand the palette can be represented without a palette.

This supports all possible conversions between “L”, “RGB” and “CMYK”. Thematrix argument only supports “L” and “RGB”.

When translating a color image to grayscale (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 grayscale (“L”) or “RGB”image into a bilevel (mode “1”) image uses Floyd-Steinbergdither to approximate the original image luminosity levels. Ifdither isNone, all values larger than 127 are set to 255 (white),all other values to 0 (black). To use other thresholds, use thepoint() method.

When converting from “RGBA” to “P” without amatrix argument,this passes the operation toquantize(),anddither andpalette are ignored.

When converting from “PA”, if an “RGBA” palette is present, the alphachannel from the image will be used instead of the values from the palette.

Parameters:
  • mode – The requested mode. See:Modes.

  • matrix – An optional conversion matrix. If given, thisshould be 4- or 12-tuple containing floating point values.

  • dither – Dithering method, used when converting frommode “RGB” to “P” or from “RGB” or “L” to “1”.Available methods areDither.NONE orDither.FLOYDSTEINBERG(default). Note that this is not used whenmatrix is supplied.

  • palette – Palette to use when converting from mode “RGB”to “P”. Available palettes arePalette.WEB orPalette.ADAPTIVE.

  • colors – Number of colors to use for thePalette.ADAPTIVEpalette. Defaults to 256.

Return type:

Image

Returns:

AnImage object.

The following example converts an RGB image (linearly calibrated according toITU-R 709, using the D65 luminant) to the CIE XYZ color space:

rgb2xyz=(0.412453,0.357580,0.180423,0,0.212671,0.715160,0.072169,0,0.019334,0.119193,0.950227,0)out=im.convert("RGB",rgb2xyz)
Image.copy()Image[source]

Copies this image. Use this method if you wish to paste thingsinto an image, but still retain the original.

Return type:

Image

Returns:

AnImage object.

Image.crop(box:tuple[float,float,float,float]|None=None)Image[source]

Returns a rectangular region from this image. The box is a4-tuple defining the left, upper, right, and lower pixelcoordinate. SeeCoordinate system.

Note: Prior to Pillow 3.4.0, this was a lazy operation.

Parameters:

box – The crop rectangle, as a (left, upper, right, lower)-tuple.

Return type:

Image

Returns:

AnImage object.

This crops the input image with the provided coordinates:

fromPILimportImagewithImage.open("hopper.jpg")asim:# The crop method from the Image module takes four coordinates as input.# The right can also be represented as (left+width)# and lower can be represented as (upper+height).(left,upper,right,lower)=(20,20,100,100)# Here the image "im" is cropped and assigned to new variable im_cropim_crop=im.crop((left,upper,right,lower))
Image.draft(mode:str|None,size:tuple[int,int]|None)tuple[str,tuple[int,int,float,float]]|None[source]

Configures the image file loader so it returns a version of theimage that as closely as possible matches the given mode andsize. For example, you can use this method to convert a colorJPEG to grayscale while loading it.

If any changes are made, returns a tuple with the chosenmode andbox with coordinates of the original image within the altered one.

Note that this method modifies theImage objectin place. If the image has already been loaded, this method has noeffect.

Note: This method is not implemented for most images. It iscurrently implemented only for JPEG and MPO images.

Parameters:
  • mode – The requested mode.

  • size – The requested size in pixels, as a 2-tuple:(width, height).

Image.effect_spread(distance:int)Image[source]

Randomly spread pixels in an image.

Parameters:

distance – Distance to spread pixels.

Image.entropy(mask:Image|None=None,extrema:tuple[float,float]|None=None)float[source]

Calculates and returns the entropy for the image.

A bilevel image (mode “1”) is treated as a grayscale (“L”)image by this method.

If a mask is provided, the method employs the histogram forthose parts of the image where the mask image is non-zero.The mask image must have the same size as the image, and beeither a bi-level image (mode “1”) or a grayscale image (“L”).

Parameters:
  • mask – An optional mask.

  • extrema – An optional tuple of manually-specified extrema.

Returns:

A float value representing the image entropy

Image.filter(filter:ImageFilter.Filter|type[ImageFilter.Filter])Image[source]

Filters this image using the given filter. For a list ofavailable filters, see theImageFilter module.

Parameters:

filter – Filter kernel.

Returns:

AnImage object.

This blurs the input image using a filter from theImageFilter module:

fromPILimportImage,ImageFilterwithImage.open("hopper.jpg")asim:# Blur the input image using the filter ImageFilter.BLURim_blurred=im.filter(filter=ImageFilter.BLUR)
Image.frombytes(data:bytes|bytearray|SupportsArrayInterface,decoder_name:str='raw',*args:Any)None[source]

Loads this image with pixel data from a bytes object.

This method is similar to thefrombytes() function,but loads data into this image instead of creating a new image object.

Image.getbands()tuple[str,...][source]

Returns a tuple containing the name of each band in this image.For example,getbands on an RGB image returns (“R”, “G”, “B”).

Returns:

A tuple containing band names.

Return type:

tuple

This helps to get the bands of the input image:

fromPILimportImagewithImage.open("hopper.jpg")asim:print(im.getbands())# Returns ('R', 'G', 'B')
Image.getbbox(*,alpha_only:bool=True)tuple[int,int,int,int]|None[source]

Calculates the bounding box of the non-zero regions in theimage.

Parameters:

alpha_only – Optional flag, defaulting toTrue.IfTrue and the image has an alpha channel, trim transparent pixels.Otherwise, trim pixels when all channels are zero.Keyword-only argument.

Returns:

The bounding box is returned as a 4-tuple defining theleft, upper, right, and lower pixel coordinate. SeeCoordinate system. If the image is completely empty, thismethod returns None.

This helps to get the bounding box coordinates of the input image:

fromPILimportImagewithImage.open("hopper.jpg")asim:print(im.getbbox())# Returns four coordinates in the format (left, upper, right, lower)
Image.getchannel(channel:int|str)Image[source]

Returns an image containing a single channel of the source image.

Parameters:

channel – What channel to return. Could be index(0 for “R” channel of “RGB”) or channel name(“A” for alpha channel of “RGBA”).

Returns:

An image in “L” mode.

Added in version 4.3.0.

Image.getcolors(maxcolors:int=256)list[tuple[int,tuple[int,...]]]|list[tuple[int,float]]|None[source]

Returns a list of colors used in this image.

The colors will be in the image’s mode. For example, an RGB image willreturn a tuple of (red, green, blue) color values, and a P image willreturn the index of the color in the palette.

Parameters:

maxcolors – Maximum number of colors. If this number isexceeded, this method returns None. The default limit is256 colors.

Returns:

An unsorted list of (count, pixel) values.

Image.getdata(band:int|None=None)core.ImagingCore[source]

Returns the contents of this image as a sequence objectcontaining pixel values. The sequence object is flattened, sothat values for line one follow directly after the values ofline zero, and so on.

Note that the sequence object returned by this method is aninternal PIL data type, which only supports certain sequenceoperations. To convert it to an ordinary sequence (e.g. forprinting), uselist(im.getdata()).

Parameters:

band – What band to return. The default is to returnall bands. To return a single band, pass in the indexvalue (e.g. 0 to get the “R” band from an “RGB” image).

Returns:

A sequence-like object.

Image.getexif()Exif[source]

Gets EXIF data from the image.

Returns:

anExif object.

Image.getextrema()tuple[float,float]|tuple[tuple[int,int],...][source]

Gets the minimum and maximum pixel values for each band inthe image.

Returns:

For a single-band image, a 2-tuple containing theminimum and maximum pixel value. For a multi-band image,a tuple containing one 2-tuple for each band.

Image.getpalette(rawmode:str|None='RGB')list[int]|None[source]

Returns the image palette as a list.

Parameters:

rawmode

The mode in which to return the palette.None willreturn the palette in its current mode.

Added in version 9.1.0.

Returns:

A list of color values [r, g, b, …], or None if theimage has no palette.

Image.getpixel(xy:tuple[int,int]|list[int])float|tuple[int,...]|None[source]

Returns the pixel value at a given position.

Parameters:

xy – The coordinate, given as (x, y). SeeCoordinate system.

Returns:

The pixel value. If the image is a multi-layer image,this method returns a tuple.

Image.getprojection()tuple[list[int],list[int]][source]

Get projection to x and y axes

Returns:

Two sequences, indicating where there are non-zeropixels along the X-axis and the Y-axis, respectively.

Image.getxmp()dict[str,Any][source]

Returns a dictionary containing the XMP tags.Requires defusedxml to be installed.

Returns:

XMP tags in a dictionary.

Image.histogram(mask:Image|None=None,extrema:tuple[float,float]|None=None)list[int][source]

Returns a histogram for the image. The histogram is returned as alist of pixel counts, one for each pixel value in the sourceimage. Counts are grouped into 256 bins for each band, even ifthe image has more than 8 bits per band. If the image has morethan one band, the histograms for all bands are concatenated (forexample, the histogram for an “RGB” image contains 768 values).

A bilevel image (mode “1”) is treated as a grayscale (“L”) imageby this method.

If a mask is provided, the method returns a histogram for thoseparts of the image where the mask image is non-zero. The maskimage must have the same size as the image, and be either abi-level image (mode “1”) or a grayscale image (“L”).

Parameters:
  • mask – An optional mask.

  • extrema – An optional tuple of manually-specified extrema.

Returns:

A list containing pixel counts.

Image.paste(im:Image|str|float|tuple[float,...],box:Image|tuple[int,int,int,int]|tuple[int,int]|None=None,mask:Image|None=None)None[source]

Pastes another image into this image. The box argument is eithera 2-tuple giving the upper left corner, a 4-tuple defining theleft, upper, right, and lower pixel coordinate, or None (same as(0, 0)). SeeCoordinate system. If a 4-tuple is given, the sizeof the pasted image must match the size of the region.

If the modes don’t match, the pasted image is converted to the mode ofthis image (see theconvert() method fordetails).

Instead of an image, the source can be a integer or tuplecontaining pixel values. The method then fills the regionwith the given color. When creating RGB images, you canalso use color strings as supported by the ImageColor module. SeeColors for more information.

If a mask is given, this method updates only the regionsindicated by the mask. You can use either “1”, “L”, “LA”, “RGBA”or “RGBa” images (if present, the alpha band is used as mask).Where the mask is 255, the given image is copied as is. Wherethe mask is 0, the current value is preserved. Intermediatevalues will mix the two images together, including their alphachannels if they have them.

Seealpha_composite() if you want tocombine images with respect to their alpha channels.

Parameters:
  • im – Source image or pixel value (integer, float or tuple).

  • box

    An optional 4-tuple giving the region to paste into.If a 2-tuple is used instead, it’s treated as the upper leftcorner. If omitted or None, the source is pasted into theupper left corner.

    If an image is given as the second argument and there is nothird, the box defaults to (0, 0), and the second argumentis interpreted as a mask image.

  • mask – An optional mask image.

Image.point(lut:Sequence[float]|NumpyArray|Callable[[int],float]|Callable[[ImagePointTransform],ImagePointTransform|float]|ImagePointHandler,mode:str|None=None)Image[source]

Maps this image through a lookup table or function.

Parameters:
  • lut

    A lookup table, containing 256 (or 65536 ifself.mode==”I” and mode == “L”) values per band in theimage. A function can be used instead, it should take asingle argument. The function is called once for eachpossible pixel value, and the resulting table is applied toall bands of the image.

    It may also be anImagePointHandlerobject:

    classExample(Image.ImagePointHandler):defpoint(self,im:Image)->Image:# Return result

  • mode – Output mode (default is same as input). This can only be used ifthe source image has mode “L” or “P”, and the output has mode “1” or thesource image mode is “I” and the output mode is “L”.

Returns:

AnImage object.

Image.putalpha(alpha:Image|int)None[source]

Adds or replaces the alpha layer in this image. If the imagedoes not have an alpha layer, it’s converted to “LA” or “RGBA”.The new layer must be either “L” or “1”.

Parameters:

alpha – The new alpha layer. This can either be an “L” or “1”image having the same size as this image, or an integer.

Image.putdata(data:Sequence[float]|Sequence[Sequence[int]]|core.ImagingCore|NumpyArray,scale:float=1.0,offset:float=0.0)None[source]

Copies pixel data from a flattened sequence object into the image. Thevalues should start at the upper left corner (0, 0), continue to theend of the line, followed directly by the first value of the secondline, and so on. Data will be read until either the image or thesequence ends. The scale and offset values are used to adjust thesequence values:pixel = value*scale + offset.

Parameters:
  • data – A flattened sequence object. SeeColors for moreinformation about values.

  • scale – An optional scale value. The default is 1.0.

  • offset – An optional offset value. The default is 0.0.

Image.putpalette(data:ImagePalette.ImagePalette|bytes|Sequence[int],rawmode:str='RGB')None[source]

Attaches a palette to this image. The image must be a “P”, “PA”, “L”or “LA” image.

The palette sequence must contain at most 256 colors, made up of oneinteger value for each channel in the raw mode.For example, if the raw mode is “RGB”, then it can contain at most 768values, made up of red, green and blue values for the corresponding pixelindex in the 256 colors.If the raw mode is “RGBA”, then it can contain at most 1024 values,containing red, green, blue and alpha values.

Alternatively, an 8-bit string may be used instead of an integer sequence.

Parameters:
  • data – A palette sequence (either a list or a string).

  • rawmode – The raw mode of the palette. Either “RGB”, “RGBA”, or a modethat can be transformed to “RGB” or “RGBA” (e.g. “R”, “BGR;15”, “RGBA;L”).

Image.putpixel(xy:tuple[int,int],value:float|tuple[int,...]|list[int])None[source]

Modifies the pixel at the given position. The color is given asa single numerical value for single-band images, and a tuple formulti-band images. In addition to this, RGB and RGBA tuples areaccepted for P and PA images. SeeColors for more information.

Note that this method is relatively slow. For more extensive changes,usepaste() or theImageDrawmodule instead.

See:

Parameters:
  • xy – The pixel coordinate, given as (x, y). SeeCoordinate system.

  • value – The pixel value.

Image.quantize(colors:int=256,method:int|None=None,kmeans:int=0,palette:Image|None=None,dither:Dither=Dither.FLOYDSTEINBERG)Image[source]

Convert the image to ‘P’ mode with the specified numberof colors.

Parameters:
Returns:

A new image

Image.reduce(factor:int|tuple[int,int],box:tuple[int,int,int,int]|None=None)Image[source]

Returns a copy of the image reducedfactor times.If the size of the image is not dividable byfactor,the resulting size will be rounded up.

Parameters:
  • factor – A greater than 0 integer or tuple of two integersfor width and height separately.

  • box – An optional 4-tuple of ints providingthe source image region to be reduced.The values must be within(0,0,width,height) rectangle.If omitted orNone, the entire source is used.

Image.remap_palette(dest_map:list[int],source_palette:bytes|bytearray|None=None)Image[source]

Rewrites the image to reorder the palette.

Parameters:
  • dest_map – A list of indexes into the original palette.e.g.[1,0] would swap a two item palette, andlist(range(256))is the identity transform.

  • source_palette – Bytes or None.

Returns:

AnImage object.

Image.resize(size:tuple[int,int]|list[int]|NumpyArray,resample:int|None=None,box:tuple[float,float,float,float]|None=None,reducing_gap:float|None=None)Image[source]

Returns a resized copy of this image.

Parameters:
  • size – The requested size in pixels, as a tuple or array:(width, height).

  • resample – An optional resampling filter. This can beone ofResampling.NEAREST,Resampling.BOX,Resampling.BILINEAR,Resampling.HAMMING,Resampling.BICUBIC orResampling.LANCZOS.If the image has mode “1” or “P”, it is always set toResampling.NEAREST. Otherwise, the default filter isResampling.BICUBIC. See:Filters.

  • box – An optional 4-tuple of floats providingthe source image region to be scaled.The values must be within (0, 0, width, height) rectangle.If omitted or None, the entire source is used.

  • reducing_gap – Apply optimization by resizing the imagein two steps. First, reducing the image by integer timesusingreduce().Second, resizing using regular resampling. The last stepchanges size no less than byreducing_gap times.reducing_gap may be None (no first step is performed)or should be greater than 1.0. The biggerreducing_gap,the closer the result to the fair resampling.The smallerreducing_gap, the faster resizing.Withreducing_gap greater or equal to 3.0, the result isindistinguishable from fair resampling in most cases.The default value is None (no optimization).

Returns:

AnImage object.

This resizes the given image from(width,height) to(width/2,height/2):

fromPILimportImagewithImage.open("hopper.jpg")asim:# Provide the target width and height of the image(width,height)=(im.width//2,im.height//2)im_resized=im.resize((width,height))
Image.rotate(angle:float,resample:Resampling=Resampling.NEAREST,expand:int|bool=False,center:tuple[float,float]|None=None,translate:tuple[int,int]|None=None,fillcolor:float|tuple[float,...]|str|None=None)Image[source]

Returns a rotated copy of this image. This method returns acopy of this image, rotated the given number of degrees counterclockwise around its centre.

Parameters:
  • angle – In degrees counter clockwise.

  • resample – An optional resampling filter. This can beone ofResampling.NEAREST (use nearest neighbour),Resampling.BILINEAR (linear interpolation in a 2x2environment), orResampling.BICUBIC (cubic splineinterpolation in a 4x4 environment). If omitted, or if the image hasmode “1” or “P”, it is set toResampling.NEAREST.SeeFilters.

  • expand – Optional expansion flag. If true, expands the outputimage to make it large enough to hold the entire rotated image.If false or omitted, make the output image the same size as theinput image. Note that the expand flag assumes rotation aroundthe center and no translation.

  • center – Optional center of rotation (a 2-tuple). Origin isthe upper left corner. Default is the center of the image.

  • translate – An optional post-rotate translation (a 2-tuple).

  • fillcolor – An optional color for area outside the rotated image.

Returns:

AnImage object.

This rotates the input image bytheta degrees counter clockwise:

fromPILimportImagewithImage.open("hopper.jpg")asim:# Rotate the image by 60 degrees counter clockwisetheta=60# Angle is in degrees counter clockwiseim_rotated=im.rotate(angle=theta)
Image.save(fp:StrOrBytesPath|IO[bytes],format:str|None=None,**params:Any)None[source]

Saves this image under the given filename. If no format isspecified, the format to use is determined from the filenameextension, if possible.

Keyword options can be used to provide additional instructionsto the writer. If a writer doesn’t recognise an option, it issilently ignored. The available options are described in theimage format documentation for each writer.

You can use a file object instead of a filename. In this case,you must always specify the format. The file object mustimplement theseek,tell, andwritemethods, and be opened in binary mode.

Parameters:
  • fp – A filename (string), os.PathLike object or file object.

  • format – Optional format override. If omitted, theformat to use is determined from the filename extension.If a file object was used instead of a filename, thisparameter should always be used.

  • params

    Extra parameters to the image writer. These can also beset on the image itself throughencoderinfo. This is useful whensaving multiple images:

    # Saving XMP data to a single imagefromPILimportImagered=Image.new("RGB",(1,1),"#f00")red.save("out.mpo",xmp=b"test")# Saving XMP data to the second frame of an imagefromPILimportImageblack=Image.new("RGB",(1,1))red=Image.new("RGB",(1,1),"#f00")red.encoderinfo={"xmp":b"test"}black.save("out.mpo",save_all=True,append_images=[red])

Returns:

None

Raises:
  • ValueError – If the output format could not be determinedfrom the file name. Use the format option to solve this.

  • OSError – If the file could not be written. The filemay have been created, and may contain partial data.

Image.seek(frame:int)None[source]

Seeks to the given frame in this sequence file. If you seekbeyond the end of the sequence, the method raises anEOFError exception. When a sequence file is opened, thelibrary automatically seeks to frame 0.

Seetell().

If defined,n_frames refers to thenumber of available frames.

Parameters:

frame – Frame number, starting at 0.

Raises:

EOFError – If the call attempts to seek beyond the endof the sequence.

Image.show(title:str|None=None)None[source]

Displays this image. This method is mainly intended for debugging purposes.

This method callsPIL.ImageShow.show() internally. You can usePIL.ImageShow.register() to override its default behaviour.

The image is first saved to a temporary file. By default, it will be inPNG format.

On Unix, the image is then opened using thexdg-open,display,gm,eog orxv utility, depending on which one can be found.

On macOS, the image is opened with the native Preview application.

On Windows, the image is opened with the standard PNG display utility.

Parameters:

title – Optional title to use for the image window, where possible.

Image.split()tuple[Image,...][source]

Split this image into individual bands. This method returns atuple of individual image bands from an image. For example,splitting an “RGB” image creates three new images eachcontaining a copy of one of the original bands (red, green,blue).

If you need only one band,getchannel()method can be more convenient and faster.

Returns:

A tuple containing bands.

Image.tell()int[source]

Returns the current frame number. Seeseek().

If defined,n_frames refers to thenumber of available frames.

Returns:

Frame number, starting with 0.

Image.thumbnail(size:tuple[float,float],resample:Resampling=Resampling.BICUBIC,reducing_gap:float|None=2.0)None[source]

Make this image into a thumbnail. This method modifies theimage to contain a thumbnail version of itself, no larger thanthe given size. This method calculates an appropriate thumbnailsize to preserve the aspect of the image, calls thedraft() method to configure the file reader(where applicable), and finally resizes the image.

Note that this function modifies theImageobject in place. If you need to use the full resolution image as well,apply this method to acopy() of the originalimage.

Parameters:
  • size – The requested size in pixels, as a 2-tuple:(width, height).

  • resample – Optional resampling filter. This can be oneofResampling.NEAREST,Resampling.BOX,Resampling.BILINEAR,Resampling.HAMMING,Resampling.BICUBIC orResampling.LANCZOS.If omitted, it defaults toResampling.BICUBIC.(wasResampling.NEAREST prior to version 2.5.0).See:Filters.

  • reducing_gap – Apply optimization by resizing the imagein two steps. First, reducing the image by integer timesusingreduce() ordraft() for JPEG images.Second, resizing using regular resampling. The last stepchanges size no less than byreducing_gap times.reducing_gap may be None (no first step is performed)or should be greater than 1.0. The biggerreducing_gap,the closer the result to the fair resampling.The smallerreducing_gap, the faster resizing.Withreducing_gap greater or equal to 3.0, the result isindistinguishable from fair resampling in most cases.The default value is 2.0 (very close to fair resamplingwhile still being faster in many cases).

Returns:

None

Image.tobitmap(name:str='image')bytes[source]

Returns the image converted to an X11 bitmap.

Note

This method only works for mode “1” images.

Parameters:

name – The name prefix to use for the bitmap variables.

Returns:

A string containing an X11 bitmap.

Raises:

ValueError – If the mode is not “1”

Image.tobytes(encoder_name:str='raw',*args:Any)bytes[source]

Return image as a bytes object.

Warning

This method returns raw image data derived from Pillow’s internalstorage. For compressed image data (e.g. PNG, JPEG) usesave(), with a BytesIO parameter for in-memory data.

Parameters:
  • encoder_name

    What encoder to use.

    The default is to use the standard “raw” encoder.To see how this packs pixel data into the returnedbytes, seelibImaging/Pack.c.

    A list of C encoders can be seen under codecssection of the function array in_imaging.c. Python encoders are registeredwithin the relevant plugins.

  • args – Extra arguments to the encoder.

Returns:

Abytes object.

Image.transform(size:tuple[int,int],method:Transform|ImageTransformHandler|SupportsGetData,data:Sequence[Any]|None=None,resample:int=Resampling.NEAREST,fill:int=1,fillcolor:float|tuple[float,...]|str|None=None)Image[source]

Transforms this image. This method creates a new image with thegiven size, and the same mode as the original, and copies datato the new image using the given transform.

Parameters:
  • size – The output size in pixels, as a 2-tuple:(width, height).

  • method

    The transformation method. This is one ofTransform.EXTENT (cut out a rectangular subregion),Transform.AFFINE (affine transform),Transform.PERSPECTIVE (perspective transform),Transform.QUAD (map a quadrilateral to a rectangle), orTransform.MESH (map a number of source quadrilateralsin one operation).

    It may also be anImageTransformHandlerobject:

    classExample(Image.ImageTransformHandler):deftransform(self,size,data,resample,fill=1):# Return result

    Implementations ofImageTransformHandlerfor some of theTransform methods are providedinImageTransform.

    It may also be an object with amethod.getdata methodthat returns a tuple supplying newmethod anddata values:

    classExample:defgetdata(self):method=Image.Transform.EXTENTdata=(0,0,100,100)returnmethod,data

  • data – Extra data to the transformation method.

  • resample – Optional resampling filter. It can be one ofResampling.NEAREST (use nearest neighbour),Resampling.BILINEAR (linear interpolation in a 2x2environment), orResampling.BICUBIC (cubic splineinterpolation in a 4x4 environment). If omitted, or if the imagehas mode “1” or “P”, it is set toResampling.NEAREST.See:Filters.

  • fill – Ifmethod is anImageTransformHandler object, this is one ofthe arguments passed to it. Otherwise, it is unused.

  • fillcolor – Optional fill color for the area outside thetransform in the output image.

Returns:

AnImage object.

Image.transpose(method:Transpose)Image[source]

Transpose image (flip or rotate in 90 degree steps)

Parameters:

method – One ofTranspose.FLIP_LEFT_RIGHT,Transpose.FLIP_TOP_BOTTOM,Transpose.ROTATE_90,Transpose.ROTATE_180,Transpose.ROTATE_270,Transpose.TRANSPOSE orTranspose.TRANSVERSE.

Returns:

Returns a flipped or rotated copy of this image.

This flips the input image by using theTranspose.FLIP_LEFT_RIGHTmethod.

fromPILimportImagewithImage.open("hopper.jpg")asim:# Flip the image from left to rightim_flipped=im.transpose(method=Image.Transpose.FLIP_LEFT_RIGHT)# To flip the image from top to bottom,# use the method "Image.Transpose.FLIP_TOP_BOTTOM"
Image.verify()None[source]

Verifies the contents of a file. For data read from a file, thismethod attempts to determine if the file is broken, withoutactually decoding the image data. If this method finds anyproblems, it raises suitable exceptions. If you need to loadthe image after using this method, you must reopen the imagefile.

Image.load()core.PixelAccess|None[source]

Allocates storage for the image and loads the pixel data. Innormal cases, you don’t need to call this method, since theImage class automatically loads an opened image when it isaccessed for the first time.

If the file associated with the image was opened by Pillow, then thismethod will close it. The exception to this is if the image hasmultiple frames, in which case the file will be left open for seekoperations. SeeFile handling in Pillow for more information.

Returns:

An image access object.

Return type:

PixelAccess

Image.close()None[source]

This operation will destroy the image core and release its memory.The image data will be unusable afterward.

This function is required to close images that have multiple frames orhave not had their file read and closed by theload() method. SeeFile handling in Pillow formore information.

Image attributes

Instances of theImage class have the following attributes:

Image.filename:str

The filename or path of the source file. Only images created with thefactory functionopen have a filename attribute. If the input is afile like object, the filename attribute is set to an empty string.

Image.format:str|None

The file format of the source file. For images created by the libraryitself (via a factory function, or by running a method on an existingimage), this attribute is set toNone.

Image.mode:str

Image mode. This is a string specifying the pixel format used by the image.Typical values are “1”, “L”, “RGB”, or “CMYK.” SeeModes for a full list.

Image.size:tuple[int]

Image size, in pixels. The size is given as a 2-tuple (width, height).

Image.width:int

Image width, in pixels.

Image.height:int

Image height, in pixels.

Image.palette:PIL.ImagePalette.ImagePalette|None

Colour palette table, if any. If mode is “P” or “PA”, this should be aninstance of theImagePalette class.Otherwise, it should be set toNone.

Image.info:dict

A dictionary holding data associated with the image. This dictionary isused by file handlers to pass on various non-image information read fromthe file. See documentation for the various file handlers for details.

Most methods ignore the dictionary when returning new images; since thekeys are not standardized, it’s not possible for a method to know if theoperation affects the dictionary. If you need the information later on,keep a reference to the info dictionary returned from the open method.

Unless noted elsewhere, this dictionary does not affect saving files.

Image.is_animated:bool

True if this image has more than one frame, orFalse otherwise.

This attribute is only defined by image plugins that support animated images.Plugins may leave this attribute undefined if they don’t support loadinganimated images, even if the given format supports animated images.

Given that this attribute is not present for all images usegetattr(image,"is_animated",False) to check if Pillow is aware of multipleframes in an image regardless of its format.

Image.n_frames:int

The number of frames in this image.

This attribute is only defined by image plugins that support animated images.Plugins may leave this attribute undefined if they don’t support loadinganimated images, even if the given format supports animated images.

Given that this attribute is not present for all images usegetattr(image,"n_frames",1) to check the number of frames that Pillow isaware of in an image regardless of its format.

Image.has_transparency_data

Determine if an image has transparency data, whether in the form of analpha channel, a palette with an alpha channel, or a “transparency” keyin the info dictionary.

Note the image might still appear solid, if all of the values shownwithin are opaque.

Returns:

A boolean.

Classes

classPIL.Image.Exif[source]

Bases:MutableMapping

This class provides read and write access to EXIF image data:

fromPILimportImageim=Image.open("exif.png")exif=im.getexif()# Returns an instance of this class

Information can be read and written, iterated over or deleted:

print(exif[274])# 1exif[274]=2fork,vinexif.items():print("Tag",k,"Value",v)# Tag 274 Value 2delexif[274]

To access information beyond IFD0,get_ifd()returns a dictionary:

fromPILimportExifTagsim=Image.open("exif_gps.jpg")exif=im.getexif()gps_ifd=exif.get_ifd(ExifTags.IFD.GPSInfo)print(gps_ifd)

Other IFDs includeExifTags.IFD.Exif,ExifTags.IFD.MakerNote,ExifTags.IFD.Interop andExifTags.IFD.IFD1.

ExifTags also has enum classes to provide names for data:

print(exif[ExifTags.Base.Software])# PILprint(gps_ifd[ExifTags.GPS.GPSDateStamp])# 1999:99:99 99:99:99
bigtiff=False
endian:str|None=None
get_ifd(tag:int)dict[int,Any][source]
hide_offsets()None[source]
load(data:bytes)None[source]
load_from_fp(fp:IO[bytes],offset:int|None=None)None[source]
tobytes(offset:int=8)bytes[source]
classPIL.Image.ImagePointHandler[source]

Used as a mixin by point transforms(for use withpoint())

classPIL.Image.ImagePointTransform(scale:float,offset:float)[source]

Used withpoint() for single band images with more than8 bits, this represents an affine transformation, where the value is multiplied byscale andoffset is added.

classPIL.Image.ImageTransformHandler[source]

Used as a mixin by geometry transforms(for use withtransform())

Protocols

classPIL.Image.SupportsArrayInterface(*args,**kwargs)[source]

Bases:Protocol

An object that has an__array_interface__ dictionary.

classPIL.Image.SupportsArrowArrayInterface(*args,**kwargs)[source]

Bases:Protocol

An object that has an__arrow_c_array__ method corresponding to the arrow cdata interface.

classPIL.Image.SupportsGetData(*args,**kwargs)[source]

Bases:Protocol

Constants

PIL.Image.NONE
PIL.Image.MAX_IMAGE_PIXELS

Set to 89,478,485, approximately 0.25GB for a 24-bit (3 bpp) image.Seeopen() for more information about how this is used.

PIL.Image.WARN_POSSIBLE_FORMATS

Set to false. If true, when an image cannot be identified, warnings will be raisedfrom formats that attempted to read the data.

Transpose methods

Used to specify theImage.transpose() method to use.

classPIL.Image.Transpose(*values)[source]
FLIP_LEFT_RIGHT=0
FLIP_TOP_BOTTOM=1
ROTATE_180=3
ROTATE_270=4
ROTATE_90=2
TRANSPOSE=5
TRANSVERSE=6

Transform methods

Used to specify theImage.transform() method to use.

classPIL.Image.Transform[source]
AFFINE

Affine transform

EXTENT

Cut out a rectangular subregion

PERSPECTIVE

Perspective transform

QUAD

Map a quadrilateral to a rectangle

MESH

Map a number of source quadrilaterals in one operation

Resampling filters

SeeFilters for details.

classPIL.Image.Resampling(*values)[source]
BICUBIC=3
BILINEAR=2
BOX=4
HAMMING=5
LANCZOS=1
NEAREST=0

Dither modes

Used to specify the dithering method to use for theconvert() andquantize() methods.

classPIL.Image.Dither[source]
NONE

No dither

ORDERED

Not implemented

RASTERIZE

Not implemented

FLOYDSTEINBERG

Floyd-Steinberg dither

Palettes

Used to specify the palette to use for theconvert() method.

classPIL.Image.Palette(*values)[source]
ADAPTIVE=1
WEB=0

Quantization methods

Used to specify the quantization method to use for thequantize() method.

classPIL.Image.Quantize[source]
MEDIANCUT

Median cut. Default method, except for RGBA images. This method does not supportRGBA images.

MAXCOVERAGE

Maximum coverage. This method does not support RGBA images.

FASTOCTREE

Fast octree. Default method for RGBA images.

LIBIMAGEQUANT

libimagequant

Check support usingPIL.features.check_feature() withfeature="libimagequant".

On this page

[8]ページ先頭

©2009-2025 Movatter.jp