Reputation: 149
This is my now code (it could crop image to 25 piece jpg from one image)
# -*- coding:utf-8 -*-
from PIL import Image
def cut(id,vx,vy):
# 打開圖片(open image)
name1 = "C:\\Users\\admin\\Desktop\\normal_random_crop\\test.png"
name2 = "C:\\Users\\admin\\Desktop\\normal_random_crop\\test_" + id + "_crop.jpg"
im =Image.open(name1)
#偏移量(offset)
dx = 100
dy = 100
n = 1
#左上角切割(Left Top Poit)
x1 = 0
y1 = 0
x2 = vx
y2 = vy
#縱向(Vertical)
while x2 <= 512:
#橫向切(Horizontal)
while y2 <= 512:
name3 = name2 + str(n) + ".jpg"
im2 = im.crop((y1, x1, y2, x2))
im2.save(name3)
y1 = y1 + dy
y2 = y1 + vy
n = n + 1
x1 = x1 + dx
x2 = x1 + vx
y1 = 0
y2 = vy
return n-1
if __name__=="__main__":
id = "1"
#切割圖片的面積 vx,vy (Crop Area)
res = cut(id,100,100)
print(res)
i hope to make generate amount random crop and specific every area specific probability for example : random crop 100 piece (from 512x512 image) total 104%
(
=====1%+2%+1%=====
1%+10%+10%+10%+1%+
1%+10%+10%+10%+1%+
1%+10%+10%+10%+1%+
=====1%+2%+1%=====
)
yellow area delete(don't need)
Upvotes: 2
Views: 461
Reputation: 28693
First of all, the total probability can't be more than 100% (in least in this universe). Assuming it is 100%, you can represent the image as 1-dimensional array and then do a weighted random choice.
So if you target 25 pieces, 5x5, with probabilities of
0 1 2 1 0
1 9 10 9 1
1 10 10 10 1
1 9 10 9 1
0 1 2 1 0
then it becomes a simple list of probabilities:
[0, 1, 2, 1, 0, 1, 9, 10, 9, ... # 25 elements total]
Then you can make a weighted random choice, choose you way, for example, from here: A weighted version of random.choice
Upvotes: 1