如何在python的空白背景图像(200x200)中随机添加20张图像(10x10)?

时间:2019-04-08 15:21:34

标签: python image opencv background geometry

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

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

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

有没有办法在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张图片进行处理并将其放置在随机位置

1 个答案:

答案 0 :(得分:0)

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

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

输出图像:

enter image description here