[Python]--Python's basic image processing (image display, saving, color transformation, scaling and rotation, etc.)

Table of contents

1. Reading and writing of image files

 Steps:

Displays three common properties of image files:

example:

2. Image file processing

Commonly used image processing methods

1. Image display

2. Save the image

 3. Copy and paste images

 4. Image scaling and rotation

 5. Image color transformation

 6. Image filtering and enhancement

7. Sequence image processing


In Python, some third-party libraries are mainly used to parse binary files such as images and web pages:

  • PIL: The most commonly used image processing third-party library
  • request: A third-party library for downloading web pages through a network connection
  • beautifulsoup4: a third-party library for parsing web page formats and obtaining data

1. Reading and writing of image files

The PIL library includes 21 classes, among which the Image class is a very important class in the PIL library. The Image class provides a variety of methods for reading, writing and processing image files. To use these methods, you need to import the Image module from the PIL library. .

from PIL import Image

 Steps:

First open the file, create an image file object, then process it, and close the file after processing.

Use the open method of the image class to load an image file. If the loading fails, an IOError will be displayed. If the loading is successful, an Image object will be returned.

Image.open()

Displays three common properties of image files:

  • format: identifies the image format or source, returns None if the image was not read from a file
  • size: the width and height of the image (in pixels), return a two-tuple (width, height)
  • mode: the color mode of the image, L stands for grayscale image, RGB stands for true color image, CMYK stands for printed image

example:

from PIL import image
im=Image.open('d:\\Python\\1.jpg')
print(im.format,im.size,im.mode)

2. Image file processing

After opening the image file, various methods of the Image class or other modules can be called for processing.

Commonly used image processing methods

Image display show()
image save sava()
Image copying and pasting crop(box)、paste(region,box)
Image scaling and rotation rotate(angle)、transpose()
Image color transformation split()、merge()、convert()
Image filtering and enhancement ImageFilter module and ImageEnhance module in PIL library
sequential image processing seek()、tell()

1. Image display

show() is used to display the image.

example:

from PIL import Image
# 图像的显示
im=Image.open('csdn.webp')
im.show()

2. Save the image

 sava() is used to save images, there are two parameters: file name filename and image format format;

If the save format is not specified when calling, the image will be automatically saved according to the extension of the image file;

If the format is specified, it is stored according to the format;

sava() can realize image format conversion, for example: save csdn.jpg to png format file

example:

"""图像的保存"""
from PIL import Image
im=Image.open('csdn.webp')
im.save('csdn.jpg')

 3. Copy and paste images

crop(box) copies a rectangular image from the image. The parameter box is a four-element tuple, and the four elements represent the horizontal and vertical coordinates of the upper left corner and the lower right corner of the rectangle respectively. The coordinate system origin ( 0, 0 ) is the upper left corner of the picture. paste(region, box) pastes one image onto another. region refers to the image object to be pasted, and the variable box specifies the paste region. If it is a 2-tuple, it represents the horizontal and vertical coordinates of the upper left corner of the pasted region; if it is a 4-tuple, it represents the horizontal and vertical coordinates of the upper left and lower right corners. If empty, defaults to (0, 0) . If a 4-tuple is given, the size of the pasted image must be the same as the size of the pasting area. If the dimensions do not match, the pasted image will be converted to the mode of the current image .

example:

"""图像的拷贝与粘贴"""
from PIL import Image
im=Image.open('csdn.jpg')
#定义拷贝区域
box=(100,20,281,202)
#拷贝图像,返回新的图像对象
region=im.crop(box)
region.show()
#将图像region粘贴到图像im左上角
im.paste(region,(0,0))
#将剪裁下来的图像粘贴到原始图像上
im.save('new.jpg')
im1=Image.open('new.jpg')
im1.show()

Cropped image:

Place the cropped image in the upper left corner of the original image:

 4. Image scaling and rotation

resize(size) adjusts the image according to the size specified by the parameter size , and generates a copy file. rotate(angle) rotates the image counterclockwise according to the angle specified by the parameter angle , and generates a copy file. The transpose() method predefines some rotation methods, such as left-right inversion, up-down inversion, counterclockwise rotation (90 , 180 , 270 degrees ) , etc.

example:

"""图像的缩放与旋转"""
from PIL import Image
im=Image.open('csdn.jpg')
#缩小尺寸
im.resize((200,100))
#逆时针旋转45°
out=im.rotate(45)
out.show()
# 左右反转
out=im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
out.show()
#上下反转
out=im.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
out.show()
# 逆时针旋转90°
out=im.transpose(Image.Transpose.ROTATE_90)
out.show()

 5. Image color transformation

Images have different color modes . In RGB mode, each picture is composed of three color channels R , G , B superimposed. You can use split() to separate the three color channels, process each color separately, and then use merge() to merge several channels to form a new image. You can also use convert() to convert an image to a different color mode parameter.

 example:

"""图像的颜色变换"""
from PIL import Image
im=Image.open('csdn.jpg')
#分离三个颜色通道
r,g,b=im.split()
# 更换r、g、b颜色后合成新图像
im=Image.merge('RGB',(b,r,g))
im.show()

 

 6. Image filtering and enhancement

The ImageFilter module and ImageEnhance module in PIL provide methods for filtering and enhancing images. The ImageFilter module predefines 10 image filtering methods, which can extract image contours, image sharpening, image smoothing, etc., and are mainly implemented using the filter() method. The ImageEnhance module is specially used for image enhancement processing, which can enhance (or weaken) the brightness, contrast, chroma, etc. of the image

example:

"""图像的过滤与增强"""
from PIL import Image
from PIL import ImageFilter
from PIL import ImageEnhance
im=Image.open('csdn.jpg')
detfilter=im.filter(ImageFilter.DETAIL)#图像细节增强
detfilter.show()
confilter=im.filter(ImageFilter.CONTOUR)#图像轮廓效果
confilter.show()
smtfilter=im.filter(ImageFilter.SMOOTH)#图像平滑
smtfilter.show()
sharpfilter=im.filter(ImageFilter.SHARPEN)#图像锐化
sharpfilter.show()

enhbrightim=ImageEnhance.Brightness(im)
brightness=5
eng_bri=enhbrightim.enhance(brightness)#图像亮度增强为原来的1.5倍
eng_bri.show()
enhbrightim=ImageEnhance.Contrast(im)
contrast=5
enh_con=enhbrightim.enhance(contrast)#图像对比度增强为原1.5倍
enh_con.show()

Detail Enhancement, Contour Effect, Smoothing, Sharpening, Brightness Enhancement, Contrast Enhancement

 

 

PIL also supports direct manipulation of pixels. For example, separate ai.jpg into three color channels, strengthen or weaken one of the channels, and then use Merge to merge the channels, thereby changing the tone of the picture ( interchange of warm and cold tones ) , etc. For example, the brightness of each pixel in layer b increases by 20%.

im=Image.open('csdn.jpg')
r,g,b=im.split()
out=b.point(lambda i:i*1.2)
im=Image.merge('RGB',(r,g,b))
im.show()

7. Sequence image processing

Sequence image is to save multiple frames of images in an image file, and play them at a certain time interval to form an animation effect . A gif image is a sequence of images. PIL also provides basic processing methods for such dynamic pictures. When such an image file is opened with open() , the first frame image will be loaded automatically, and the seek() and tell() methods can be used to move between frames. seek(frame) means to jump to the specified image frame, tell() returns the serial number of the current frame

 example:

The code adopts the try-except structure. First, execute the statement in the try. When the image has jumped to the last image frame, an exception will occur if it jumps again (im.tell()+1). At this time, execute the following except statement, the program ends.

"""图像的序列操作"""
from PIL import Image
# 读入gif文件
im=Image.open('pai.gif')
try:
    im.save('frame{:02d}.png'.format(im.tell()))
    # 保存图像帧为png文件
    while True:
        # 跳转到下一帧图像
        im.seek(im.tell()+1)
        im.save('frame{:02d}.png'.format(im.tell()))
except:
    print('处理结束')


Guess you like

Origin blog.csdn.net/Tir_zhang/article/details/127586735