python image processing --- cutting is divided into equal parts by a few times (the use of the crop() function)

I am doing a graduation project recently, which involves the knowledge of image processing. If you find it useful, record it. There may not be many principles, but the important thing is to use it~ I am using python3.6, not much nonsense, first Above renderings

It can be seen that what is implemented here is a fixed-point cutting, how to achieve it? Let's take a look at the code:

from PIL import Image

im = Image.open( 'F:/test.jpg' )
# image width and height
img_size = im.size
print ( "Image width and height are {} ". format(img_size))

left = 80
upper = 210
right = 505
lower = 640

region = im.crop((left,upper,right,lower))
region.save( "F:/crop_test.jpg" )

This code realizes cutting a certain part of the specified area from a large image, mainly using the crop() function, the parameters of crop(), and after reading the following definition, we should pay attention to crop() ) function of this 4-tuple parameter

def crop ( self , box = None ):
"""
Returns a rectangular region from this image. The box is a
4-tuple defining the left, upper, right, and lower pixel
coordinate.

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

:param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""

现在具体讲怎么设置(left,upper,right,lower)这个参数,其实简单点来说就是“左上右下”的顺序,我之前那个是怎么实现切割的呢?我是怎么获取这些边界的呢,其实很笨的方法,我使用了ps的坐标,拖动的时候就可以看到对应像素,如下图:


好了,最简单的切割完成了,在这里在贴一个自动切割多块的代码,切割个数是yy * xx个,可自行修改,知道了原理大家也可以自由发挥哦~效果图和代码如下:


from PIL import Image

im = Image.open( "F:/test.jpg")
# 图片的宽度和高度
img_size = im.size
print( "图片宽度和高度分别是 {} ".format(img_size))

xx = 3
yy = 2
x = img_size[ 0] // xx
y = img_size[ 1] // yy
for j in range(yy):
for i in range(xx):
left = i*x
up = y*j
right = left + x
low = up + y
region = im.crop((left,up,right,low))
print((left,up,right,low))
temp = str(i)+ str(j)
region.save( "f:/test/"+temp+ ".png")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324540034&siteId=291194637