How to get random bounding boxes from image? (python)
<p>I have a batch of images and I open each one using the open function with mode 'rb' and then I read each one using read function. Now I want to get 50 random bounding boxes from each image and read each bounding box again with open and read functions. Is there any simple way to do it?</p>

<p>Here's a possible solution:</p>

<pre><code>from random import randint
from PIL import Image


def random_bbox(bbox):
    v = [randint(0, v) for v in bbox]
    left = min(v[0], v[2])
    upper = min(v[1], v[3])
    right = max(v[0], v[2])
    lower = max(v[1], v[3])
    return [left, upper, right, lower]

filename = "your_image.png"
im = Image.open(filename)
bbox = im.getbbox()
N = 50

for i in range(N):
    random_tile = im.crop(random_bbox(bbox))
    #random_tile.show()
</code></pre>

<p>As you can see, this solution is cropping random subimages from one image, as you can see I've commented the line <code>random_tile.show()</code>, now it's up to you how processing that random_tile (saving, tweaking, ...)</p>

python image bounding-box