【发布时间】:2020-07-04 00:39:10
【问题描述】:
我正在尝试从单个图像 (.jpg) 中裁剪方形区域。我想从左上角裁剪图片然后向右移动到下一个“图层” 像这样Save them with name 1.jpg, 2.jpg....to n.jpg 下面的代码有效,但是我想学习如何缩短我使用的代码。谢谢!!
以及如何使用相同的过程从图像中裁剪出圆形?
# Improting Image class from PIL module
from PIL import Image
import os
# Opens a image in RGB mode
im = Image.open(r"C:/Users/User/Desktop/1.jpg")
out_put_dir = 'C:/Users/User/Desktop/cropped image'
os.chdir(out_put_dir)
# Setting the points for cropped image
w, h = im.size
print(w, h)
count = 0
for a in range(h+1):
left = a
top = 0 ## First layer
right = 100 + a**strong text**
bottom = 100 ## First layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 1_'+str(count)+'.'+'jpg')
count += 1
count = 0
for a in range(h+1):
left = a
top = 100 ## Second layer
right = 100 + a
bottom = 200 ## Second layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 2_'+str(count)+'.'+'jpg')
count += 1
count = 0
for a in range(h+1):
left = a
top = 200 ## Third layer
right = 100 + a
bottom = 300 # Third layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 3_'+str(count)+'.'+'jpg')
count += 1
count = 0
for a in range(h+1):
left = a
top = 300 ## Forth layer
right = 100 + a
bottom = 400 # Forth layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 4_'+str(count)+'.'+'jpg')
count += 1
count = 0
for a in range(h+1):
left = a
top = 400 # Fifth layer
right = 100 + a
bottom = 500 # Fifth layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 5_'+str(count)+'.'+'jpg')
count += 1
count = 0
for a in range(h+1):
left = a
top = 500 # Sixth layer
right = 100 + a
bottom = 600 # Sixth layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 6_'+str(count)+'.'+'jpg')
count += 1
count = 0
for a in range(h+1):
left = a
top = 600 ## Seventh layer
right = 100 + a
bottom = 700 ## Seventh layer
im1 = im.crop((left, top, right, bottom))
im1.save('layer 7_'+str(count)+'.'+'jpg')
count += 1
【问题讨论】: