如何从图像中随机裁剪(特定区域和特定概率)矩形

问题描述 投票:2回答:1

这是我现在的代码(它可以从一个图像裁剪图像到25件jpg)

# -*- 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)

我希望使生成量随机裁剪和特定的每个区域特定概率,例如:随机裁剪100件(从512x512图像)总104%

(

=====1%+2%+1%=====

1%+10%+10%+10%+1%+

1%+10%+10%+10%+1%+

1%+10%+10%+10%+1%+

=====1%+2%+1%=====

)

黄色区域删除(不需要)

enter image description here

python random probability crop
1个回答
1
投票

首先,总概率不能超过100%(至少在这个宇宙中)。假设它是100%,您可以将图像表示为一维数组,然后进行加权随机选择。

所以,如果你的目标是25件,5x5,概率为

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

然后它成为一个简单的概率列表:

[0, 1,  2,  1,  0, 1, 9,  10, 9, ... # 25 elements total]

然后你可以做一个加权随机选择,选择你的方式,例如,从这里:A weighted version of random.choice

© www.soinside.com 2019 - 2024. All rights reserved.