python - 如何用python将图片划分为等间距的正方形?
问题描述
我正在尝试使用 PIL 并定义我自己的函数,该函数将图像和 square_size(宽度或高度)作为参数,然后将图像分成一系列所述大小的较小正方形。我不明白 PIL 的裁剪方法。它接受一个(上、左、右、下)。左上、右上等系统似乎更有用。
我在哪里,卡住的是编写代码,可以找到这些坐标应该是什么,从原点开始,给定一个正方形大小。有任何想法吗?
这是行不通的。
def parse_image(source, square_size):
src = Image.open(source)
dimensions = src.size
max_up = int(src.height/square_size)
max_right = int(src.width/square_size)
tl = 0
tr = square_size
bl = square_size * src.width + 1
br = bl + square_size
test = src.crop((tl,tr,bl,br))
test.save('test.jpg')
test.show()
解决方案
假设square_size
是一个定义每边长度的 int 并且我们想要多个图像作为结果。下面的代码未经测试,但应该可以解决您的问题
def parse_image(source, square_size):
src = Image.open(source)
width, height = src.size
image_results = []
for x in range(0, width, square_size): #
for y in range(0, height, square_size):
top_left = (x, y) #left top of the rect
bottom_right = (x+square_size, y+square_size) #right bottom of the rect
#the current format is used, because it's the cheapest
#way to explain a rectange, lookup Rects
test = src.crop((top_left[1], top_left[0], bottom_right[0], bottom_right[1]))
image_results.append(test)
return image_results
让我知道是否有任何问题!
编辑,我受到一个候选答案的启发,这个解决方案奏效了。
def parse_image(source, square_size, print_coords=False):
src = Image.open(source)
dimensions = src.size
print(f"image dimensions: {src.size}")
max_down = int(src.height/square_size) * square_size + square_size
max_right = int(src.width/square_size) * square_size + square_size
tl_x = 0
tl_y = 0
br_x = square_size
br_y = square_size
count=0
for y in range(square_size,max_down,square_size):
for x in range(square_size,max_right,square_size):
count +=1
sample = src.crop((tl_x,tl_y,br_x,br_y))
sample.save(f"{source[:-4]}_sample_{count}_x{tl_x}_y{tl_y}.jpg")
if print_coords == True:
print(f"image {count}: top-left (x,y): {(tl_x,tl_y)}, bottom-right (x,y): {(br_x,br_y)}")
tl_x = x
br_x = x + square_size
tl_x =0
br_x = square_size
tl_y = y
br_y = y + square_size
推荐阅读
- r - 在 df 中给出/取回一定数量的行
- amazon-ec2 - Windows 服务器在 5 次 RDP 登录尝试失败后重新启动
- gnuplot - Gnuplot - 绘制矩阵并用数字替换正方形
- java - 在 Picocli 的单元测试中检查选项的值
- scheme - 用 10 美分和 20 美分兑换 2 和 1 欧元的球拍功能
- sql - 如何从两个连接表的多行中检索基于多个条件的数据?
- javascript - 有什么方法可以获取不属于 Chart.js 图中数据集的特定 x 的 y?
- android - 离子cordova使用packageType构建android并将参数传递给cordova hook
- javascript - 字符串操作:我不明白在这个编码挑战中使用 str.length-1
- php - 无法在刀片文件中显示分页链接 - Laravel Livewire