如何在python的空白背景图像(200x200)中随机添加20张图像(10x10)? [英] How can I randomly add 20 images(10x10) in an empty background image (200x200) in python?

查看:344
本文介绍了如何在python的空白背景图像(200x200)中随机添加20张图像(10x10)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将10张小图像放置在此圆圈中

我正在一个小项目中,将几张大小(10 w x 10 h)的图像随机放置或放置在另一张图像中,这些图像将在python中用作大小(200 w x 200 h)的背景.这些小图像应放在背景图像中的任意位置.

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.

我有20张尺寸为(10x10)的小图像和一张尺寸为(200x200)的空白图像背景.我想将20张小图片放在背景中随机位置的空白背景图片中.

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.

有没有办法在Python中做到这一点?

Is there a way to do it in Python?

代码

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

上面的代码是针对一张图片的,我想针对20张图片进行处理并将其放置在随机位置

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

推荐答案

假设您具有背景图像background.jpg(减小到200x200像素)和10张图像:image01.pngimage02.png ... image10.png(10x10像素).然后:

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')

输出图像:

这篇关于如何在python的空白背景图像(200x200)中随机添加20张图像(10x10)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆