使用白色圆圈背景使图像更平滑

2024-05-23 14:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望这个项目用Python完成
我有这个法师,我想让我上传的每个图像都像下面的图像一样 I have this mage , I want to make each image i upload like image below
如果需要一些边框使其成为圆形,则每个图像都应该像这样被圈起来添加边框,否则不要添加任何边框并添加灰色背景 Each image should be Circled like this if some border is needed to make it Circle add border otherwise don't ad any border


Tags: 项目图像圆形边框背景灰色法师
1条回答
网友
1楼 · 发布于 2024-05-23 14:28:11

在Python OpenCV中有一种方法可以做到这一点

  • 读取输入
  • 计算最大尺寸、偏移和输入中心
  • 创建最大尺寸加上填充的白色图像
  • 将输入图像插入白色图像的中心
  • 创建与白色图像尺寸相同的灰色背景图像
  • 在灰色背景的中心画一个直径等于最大尺寸的黑色圆圈
  • 模糊黑色圆圈以创建阴影
  • 在黑色图像的中心创建一个直径等于最大尺寸的白色圆
  • 将白色背景上的图像与背景上模糊的黑色圆圈混合形成结果
  • 保存结果

输入:

enter image description here

import cv2
import numpy as np

# load image and get maximum dimension
img = cv2.imread("radio_skull.jpg")
hh, ww = img.shape[:2]
maxwh = max(ww,hh)
offx = (maxwh - ww) // 2
offy = (maxwh - hh) // 2
cx = maxwh // 2
cy = maxwh // 2
pad = 10
pad2 = 2*pad

# create white image of size maxwh plus 10 pixels padding all around
white = np.full((maxwh+pad2, maxwh+pad2, 3), (255,255,255), dtype=np.uint8)

# put input img into center of white image
img_white = white.copy()
img_white[offy+pad:offy+pad+hh, offx+pad:offx+pad+ww] = img

# create light gray background image with 10 pixel padding all around
bckgrnd = np.full((maxwh+pad2,maxwh+pad2,3), (192,192,192), dtype=np.uint8)

# create black circle on background image for drop shadow
cv2.circle(bckgrnd, (cx+pad,cy+pad), cx, (0,0,0), -1)

# blur black circle
bckgrnd = cv2.GaussianBlur(bckgrnd, (25,25), 0)

# create white circle on black background as mask
mask = np.zeros_like(img_white)
cv2.circle(mask, (cx+pad,cy+pad), cx, (255,255,255), -1)

# use mask to blend img_white and bckgrnd
img_white_circle = cv2.bitwise_and(img_white, mask)
bckgrnd_circle = cv2.bitwise_and(bckgrnd, 255-mask)
result = cv2.add(img_white_circle, bckgrnd_circle)

# write result to disk
cv2.imwrite("radio_skull_img_white.jpg", img_white)
cv2.imwrite("radio_skull_background.jpg", bckgrnd)
cv2.imwrite("radio_skull_mask.jpg", mask)
cv2.imwrite("radio_skull_img_white_circle.jpg", img_white_circle)
cv2.imwrite("radio_skull_bckgrnd_circle.jpg", bckgrnd_circle)
cv2.imwrite("radio_skull_result.jpg", result)

# display it
cv2.imshow("img_white", img_white)
cv2.imshow("bckgrnd", bckgrnd)
cv2.imshow("mask", mask)
cv2.imshow("img_white_circle", img_white_circle)
cv2.imshow("bckgrnd_circle", bckgrnd_circle)
cv2.imshow("result", result)
cv2.waitKey(0)

白色背景上的输入:

enter image description here

背景上模糊的黑色圆圈:

enter image description here

遮罩:

enter image description here

白色蒙版图像:

enter image description here

蒙面黑圈:

enter image description here

结果:

enter image description here

相关问题 更多 >