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

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

解决方案

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:

fb06c34ea3b30aa9ab585b76491094f6.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值