简体   繁体   中英

How can I randomly add 20 images(10x10) in an empty background image (200x200) in python?

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 wx 10 h) in another image that will be used as background of size (200 wx 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

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM