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

Source code for PIL.ImageFilter

## The Python Imaging Library.# $Id$## standard filters## History:# 1995-11-27 fl   Created# 2002-06-08 fl   Added rank and mode filters# 2003-09-15 fl   Fixed rank calculation in rank filter; added expand call## Copyright (c) 1997-2003 by Secret Labs AB.# Copyright (c) 1995-2002 by Fredrik Lundh.## See the README file for information on usage and redistribution.#from__future__importannotationsimportabcimportfunctoolsfromcollections.abcimportSequencefromtypingimportcastTYPE_CHECKING=FalseifTYPE_CHECKING:fromcollections.abcimportCallablefromtypesimportModuleTypefromtypingimportAnyfrom.import_imagingfrom._typingimportNumpyArray
[docs]classFilter(abc.ABC):
[docs]@abc.abstractmethoddeffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:pass
[docs]classMultibandFilter(Filter):pass
classBuiltinFilter(MultibandFilter):filterargs:tuple[Any,...]deffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:ifimage.mode=="P":msg="cannot filter palette images"raiseValueError(msg)returnimage.filter(*self.filterargs)
[docs]classKernel(BuiltinFilter):""" Create a convolution kernel. This only supports 3x3 and 5x5 integer and floating point kernels. Kernels can only be applied to "L" and "RGB" images. :param size: Kernel size, given as (width, height). This must be (3,3) or (5,5). :param kernel: A sequence containing kernel weights. The kernel will be flipped vertically before being applied to the image. :param scale: Scale factor. If given, the result for each pixel is divided by this value. The default is the sum of the kernel weights. :param offset: Offset. If given, this value is added to the result, after it has been divided by the scale factor. """name="Kernel"def__init__(self,size:tuple[int,int],kernel:Sequence[float],scale:float|None=None,offset:float=0,)->None:ifscaleisNone:# default scale is sum of kernelscale=functools.reduce(lambdaa,b:a+b,kernel)ifsize[0]*size[1]!=len(kernel):msg="not enough coefficients in kernel"raiseValueError(msg)self.filterargs=size,scale,offset,kernel
[docs]classRankFilter(Filter):""" Create a rank filter. The rank filter sorts all pixels in a window of the given size, and returns the ``rank``'th value. :param size: The kernel size, in pixels. :param rank: What pixel value to pick. Use 0 for a min filter, ``size * size / 2`` for a median filter, ``size * size - 1`` for a max filter, etc. """name="Rank"def__init__(self,size:int,rank:int)->None:self.size=sizeself.rank=rankdeffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:ifimage.mode=="P":msg="cannot filter palette images"raiseValueError(msg)image=image.expand(self.size//2,self.size//2)returnimage.rankfilter(self.size,self.rank)
[docs]classMedianFilter(RankFilter):""" Create a median filter. Picks the median pixel value in a window with the given size. :param size: The kernel size, in pixels. """name="Median"def__init__(self,size:int=3)->None:self.size=sizeself.rank=size*size//2
[docs]classMinFilter(RankFilter):""" Create a min filter. Picks the lowest pixel value in a window with the given size. :param size: The kernel size, in pixels. """name="Min"def__init__(self,size:int=3)->None:self.size=sizeself.rank=0
[docs]classMaxFilter(RankFilter):""" Create a max filter. Picks the largest pixel value in a window with the given size. :param size: The kernel size, in pixels. """name="Max"def__init__(self,size:int=3)->None:self.size=sizeself.rank=size*size-1
[docs]classModeFilter(Filter):""" Create a mode filter. Picks the most frequent pixel value in a box with the given size. Pixel values that occur only once or twice are ignored; if no pixel value occurs more than twice, the original pixel value is preserved. :param size: The kernel size, in pixels. """name="Mode"def__init__(self,size:int=3)->None:self.size=sizedeffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:returnimage.modefilter(self.size)
[docs]classGaussianBlur(MultibandFilter):"""Blurs the image with a sequence of extended box filters, which approximates a Gaussian kernel. For details on accuracy see <https://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf> :param radius: Standard deviation of the Gaussian kernel. Either a sequence of two numbers for x and y, or a single number for both. """name="GaussianBlur"def__init__(self,radius:float|Sequence[float]=2)->None:self.radius=radiusdeffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:xy=self.radiusifisinstance(xy,(int,float)):xy=(xy,xy)ifxy==(0,0):returnimage.copy()returnimage.gaussian_blur(xy)
[docs]classBoxBlur(MultibandFilter):"""Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value. :param radius: Size of the box in a direction. Either a sequence of two numbers for x and y, or a single number for both. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total. """name="BoxBlur"def__init__(self,radius:float|Sequence[float])->None:xy=radiusifisinstance(radius,(tuple,list))else(radius,radius)ifxy[0]<0orxy[1]<0:msg="radius must be >= 0"raiseValueError(msg)self.radius=radiusdeffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:xy=self.radiusifisinstance(xy,(int,float)):xy=(xy,xy)ifxy==(0,0):returnimage.copy()returnimage.box_blur(xy)
[docs]classUnsharpMask(MultibandFilter):"""Unsharp mask filter. See Wikipedia's entry on `digital unsharp masking`_ for an explanation of the parameters. :param radius: Blur Radius :param percent: Unsharp strength, in percent :param threshold: Threshold controls the minimum brightness change that will be sharpened .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking """name="UnsharpMask"def__init__(self,radius:float=2,percent:int=150,threshold:int=3)->None:self.radius=radiusself.percent=percentself.threshold=thresholddeffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:returnimage.unsharp_mask(self.radius,self.percent,self.threshold)
classBLUR(BuiltinFilter):name="Blur"# fmt: offfilterargs=(5,5),16,0,(1,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1,)# fmt: onclassCONTOUR(BuiltinFilter):name="Contour"# fmt: offfilterargs=(3,3),1,255,(-1,-1,-1,-1,8,-1,-1,-1,-1,)# fmt: onclassDETAIL(BuiltinFilter):name="Detail"# fmt: offfilterargs=(3,3),6,0,(0,-1,0,-1,10,-1,0,-1,0,)# fmt: onclassEDGE_ENHANCE(BuiltinFilter):name="Edge-enhance"# fmt: offfilterargs=(3,3),2,0,(-1,-1,-1,-1,10,-1,-1,-1,-1,)# fmt: onclassEDGE_ENHANCE_MORE(BuiltinFilter):name="Edge-enhance More"# fmt: offfilterargs=(3,3),1,0,(-1,-1,-1,-1,9,-1,-1,-1,-1,)# fmt: onclassEMBOSS(BuiltinFilter):name="Emboss"# fmt: offfilterargs=(3,3),1,128,(-1,0,0,0,1,0,0,0,0,)# fmt: onclassFIND_EDGES(BuiltinFilter):name="Find Edges"# fmt: offfilterargs=(3,3),1,0,(-1,-1,-1,-1,8,-1,-1,-1,-1,)# fmt: onclassSHARPEN(BuiltinFilter):name="Sharpen"# fmt: offfilterargs=(3,3),16,0,(-2,-2,-2,-2,32,-2,-2,-2,-2,)# fmt: onclassSMOOTH(BuiltinFilter):name="Smooth"# fmt: offfilterargs=(3,3),13,0,(1,1,1,1,5,1,1,1,1,)# fmt: onclassSMOOTH_MORE(BuiltinFilter):name="Smooth More"# fmt: offfilterargs=(5,5),100,0,(1,1,1,1,1,1,5,5,5,1,1,5,44,5,1,1,5,5,5,1,1,1,1,1,1,)# fmt: on
[docs]classColor3DLUT(MultibandFilter):"""Three-dimensional color lookup table. Transforms 3-channel pixels using the values of the channels as coordinates in the 3D lookup table and interpolating the nearest elements. This method allows you to apply almost any color transformation in constant time by using pre-calculated decimated tables. .. versionadded:: 5.2.0 :param size: Size of the table. One int or tuple of (int, int, int). Minimal size in any dimension is 2, maximum is 65. :param table: Flat lookup table. A list of ``channels * size**3`` float elements or a list of ``size**3`` channels-sized tuples with floats. Channels are changed first, then first dimension, then second, then third. Value 0.0 corresponds lowest value of output, 1.0 highest. :param channels: Number of channels in the table. Could be 3 or 4. Default is 3. :param target_mode: A mode for the result image. Should have not less than ``channels`` channels. Default is ``None``, which means that mode wouldn't be changed. """name="Color 3D LUT"def__init__(self,size:int|tuple[int,int,int],table:Sequence[float]|Sequence[Sequence[int]]|NumpyArray,channels:int=3,target_mode:str|None=None,**kwargs:bool,)->None:ifchannelsnotin(3,4):msg="Only 3 or 4 output channels are supported"raiseValueError(msg)self.size=size=self._check_size(size)self.channels=channelsself.mode=target_mode# Hidden flag `_copy_table=False` could be used to avoid extra copying# of the table if the table is specially made for the constructor.copy_table=kwargs.get("_copy_table",True)items=size[0]*size[1]*size[2]wrong_size=Falsenumpy:ModuleType|None=Noneifhasattr(table,"shape"):try:importnumpyexceptImportError:passifnumpyandisinstance(table,numpy.ndarray):numpy_table:NumpyArray=tableifcopy_table:numpy_table=numpy_table.copy()ifnumpy_table.shapein[(items*channels,),(items,channels),(size[2],size[1],size[0],channels),]:table=numpy_table.reshape(items*channels)else:wrong_size=Trueelse:ifcopy_table:table=list(table)# Convert to a flat listiftableandisinstance(table[0],(list,tuple)):raw_table=cast(Sequence[Sequence[int]],table)flat_table:list[int]=[]forpixelinraw_table:iflen(pixel)!=channels:msg=("The elements of the table should "f"have a length of{channels}.")raiseValueError(msg)flat_table.extend(pixel)table=flat_tableifwrong_sizeorlen(table)!=items*channels:msg=("The table should have either channels * size**3 float items ""or size**3 items of channels-sized tuples with floats. "f"Table should be:{channels}x{size[0]}x{size[1]}x{size[2]}. "f"Actual length:{len(table)}")raiseValueError(msg)self.table=table@staticmethoddef_check_size(size:Any)->tuple[int,int,int]:try:_,_,_=sizeexceptValueErrorase:msg="Size should be either an integer or a tuple of three integers."raiseValueError(msg)fromeexceptTypeError:size=(size,size,size)size=tuple(int(x)forxinsize)forsize_1dinsize:ifnot2<=size_1d<=65:msg="Size should be in [2, 65] range."raiseValueError(msg)returnsize
[docs]@classmethoddefgenerate(cls,size:int|tuple[int,int,int],callback:Callable[[float,float,float],tuple[float,...]],channels:int=3,target_mode:str|None=None,)->Color3DLUT:"""Generates new LUT using provided callback. :param size: Size of the table. Passed to the constructor. :param callback: Function with three parameters which correspond three color channels. Will be called ``size**3`` times with values from 0.0 to 1.0 and should return a tuple with ``channels`` elements. :param channels: The number of channels which should return callback. :param target_mode: Passed to the constructor of the resulting lookup table. """size_1d,size_2d,size_3d=cls._check_size(size)ifchannelsnotin(3,4):msg="Only 3 or 4 output channels are supported"raiseValueError(msg)table:list[float]=[0]*(size_1d*size_2d*size_3d*channels)idx_out=0forbinrange(size_3d):forginrange(size_2d):forrinrange(size_1d):table[idx_out:idx_out+channels]=callback(r/(size_1d-1),g/(size_2d-1),b/(size_3d-1))idx_out+=channelsreturncls((size_1d,size_2d,size_3d),table,channels=channels,target_mode=target_mode,_copy_table=False,)
[docs]deftransform(self,callback:Callable[...,tuple[float,...]],with_normals:bool=False,channels:int|None=None,target_mode:str|None=None,)->Color3DLUT:"""Transforms the table values using provided callback and returns a new LUT with altered values. :param callback: A function which takes old lookup table values and returns a new set of values. The number of arguments which function should take is ``self.channels`` or ``3 + self.channels`` if ``with_normals`` flag is set. Should return a tuple of ``self.channels`` or ``channels`` elements if it is set. :param with_normals: If true, ``callback`` will be called with coordinates in the color cube as the first three arguments. Otherwise, ``callback`` will be called only with actual color values. :param channels: The number of channels in the resulting lookup table. :param target_mode: Passed to the constructor of the resulting lookup table. """ifchannelsnotin(None,3,4):msg="Only 3 or 4 output channels are supported"raiseValueError(msg)ch_in=self.channelsch_out=channelsorch_insize_1d,size_2d,size_3d=self.sizetable:list[float]=[0]*(size_1d*size_2d*size_3d*ch_out)idx_in=0idx_out=0forbinrange(size_3d):forginrange(size_2d):forrinrange(size_1d):values=self.table[idx_in:idx_in+ch_in]ifwith_normals:values=callback(r/(size_1d-1),g/(size_2d-1),b/(size_3d-1),*values,)else:values=callback(*values)table[idx_out:idx_out+ch_out]=valuesidx_in+=ch_inidx_out+=ch_outreturntype(self)(self.size,table,channels=ch_out,target_mode=target_modeorself.mode,_copy_table=False,)
def__repr__(self)->str:r=[f"{self.__class__.__name__} from{self.table.__class__.__name__}","size={:d}x{:d}x{:d}".format(*self.size),f"channels={self.channels:d}",]ifself.mode:r.append(f"target_mode={self.mode}")return"<{}>".format(" ".join(r))deffilter(self,image:_imaging.ImagingCore)->_imaging.ImagingCore:from.importImagereturnimage.color_lut_3d(self.modeorimage.mode,Image.Resampling.BILINEAR,self.channels,self.size,self.table,)
Copyright © 1995-2011 Fredrik Lundh and contributors, 2010 Jeffrey A. Clark and contributors.
Made withSphinx and@pradyunsg'sFuro

[8]
ページ先頭

©2009-2025 Movatter.jp