How can I randomly add 20 images(10x10) in an empt

2019-09-19 09:05发布

I want the 10 small images to be placed in this circle

I'm working on a small project to randomly place or put several images of size (10 w x 10 h) in another image that will be used as background of size (200 w x 200 h) in python. The small images should be put at a random location in the background image.

I have 20 small images of size (10x10) and one empty image background of size (200x200). I want to put my 20 small images in the empty background image at a random location in the background.

Is there a way to do it in Python?

Code

# Depencies importation
import cv2

# Saving directory
saving_dir = "../Saved_Images/"

# Read the background image
bgimg = cv2.imread("../Images/background.jpg")

# Resizing the bacground image
bgimg_resized = cv2.resize(bgimg, (2050,2050))

# Read the image that will be put in the background image (exemple of 1)
small_img = cv2.imread("../Images/small.jpg")

# Convert the resized background image to gray
bgimg_gray = cv2.cvtColor(bgimg, cv2.COLOR_BGR2GRAY) 
# Convert the grayscale image to a binary image
ret, thresh = cv2.threshold(bgimg_gray,127,255,0)
# Determine the moments of the binary image
M = cv2.moments(thresh)
# calculate x,y coordinate of center
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

# drawing the circle in the background image
circle = cv2.circle(bgimg, (cX, cY), 930, (0,0,255), 9)

print(circle)

# Saving the new image
cv2.imwrite(saving_dir+"bgimg"+".jpg", bgimg)

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.resizeWindow("Test", 1000, 1200)
# Showing the images
cv2.imshow("image", bgimg)
# Waiting for any key to stop the program execution
cv2.waitKey(0)

the above code is for one image, I want to do it for the 20 and to put them in a random location

1条回答
干净又极端
2楼-- · 2019-09-19 09:21

Assuming you have that background image background.jpg (decreased to 200x200 px) and 10 images: image01.png, image02.png ... image10.png (10x10 px). Then:

import glob
import random
from PIL import Image


img_bg = Image.open('circle.jpg')
width, height = img_bg.size
images = glob.glob('*.png')
for img in images:
    img = Image.open(img)
    x = random.randint(40, width-40)
    y = random.randint(40, height-40)
    img_bg.paste(img, (x, y, x+10, y+10))
img_bg.save('result.png', 'PNG')

Output image:

enter image description here

查看更多
登录 后发表回答