如何使用OpenCV将图片插入到一个圆形中?

huangapple go评论70阅读模式
英文:

How to insert a picture in a circle using opencv?

问题

我需要用附加的第二张图片填充第一张图片的圆形白色部分,我应该如何在OpenCV中实现这个?

英文:

I need to fill the white part of the circle of the first image with the second image I have attached, how can I do this in opencv? 如何使用OpenCV将图片插入到一个圆形中? enter image description here

答案1

得分: 2

以下是Python/OpenCV中的一种方法:

  • 读取每个图像
  • 将圆形图像转换为灰度图
  • 对圆形图像进行阈值处理
  • 将第二个图像裁剪为第一个图像的大小
  • 使用阈值图像作为要使用的区域的选择器,将裁剪后的第二个图像与第一个图像合并
  • 保存结果
import cv2
import numpy as np

# 读取图像1
img1 = cv2.imread('white_circle.png')
h1, w1 = img1.shape[:2]

# 读取图像2
img2 = cv2.imread('bear_heart.jpg')
h2, w2 = img2.shape[:2]

# 将img1转换为灰度图
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

# 阈值处理为二值图
thresh = cv2.threshold(gray, 254, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)

# 将第二个图像裁剪为第一个图像的大小
img2_crop = img2[0:h1, 0:w1]

# 使用阈值图像作为掩码,将img1和img2_crop合并
result = np.where(thresh == 255, img2_crop, img1)

# 保存结果
cv2.imwrite('white_circle_thresh.jpg', thresh)
cv2.imwrite('white_circle_bear_heart.jpg', result)

cv2.imshow("thresh", thresh)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

阈值图像:

如何使用OpenCV将图片插入到一个圆形中?

结果图像:

如何使用OpenCV将图片插入到一个圆形中?

英文:

Here is one way in Python/OpenCV.

  • Read each image
  • Convert the circle image to grayscale
  • Threshold the circle image
  • Crop the second image to the size of the first image
  • Combine the cropped second image with the first image using the threshold image as the selector of the region to use
  • Save the results

Input 1:

如何使用OpenCV将图片插入到一个圆形中?

Input 2:

如何使用OpenCV将图片插入到一个圆形中?

import cv2
import numpy as np

# read image 1
img1 = cv2.imread('white_circle.png')
h1, w1 = img1.shape[:2]

# read image 2
img2 = cv2.imread('bear_heart.jpg')
h2, w2 = img2.shape[:2]

# convert img1 to grayscale
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

# threshold to binary
thresh = cv2.threshold(gray, 254, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)

# crop second image to size of first image
img2_crop = img2[0:h1, 0:w1]

# combine img1, img2_crop with threshold as mask
result = np.where(thresh==255, img2_crop, img1)

# save results
cv2.imwrite('white_circle_thresh.jpg', thresh)
cv2.imwrite('white_circle_bear_heart.jpg', result)

cv2.imshow("thresh", thresh)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Threshold Image:

如何使用OpenCV将图片插入到一个圆形中?

Result Image:

如何使用OpenCV将图片插入到一个圆形中?

huangapple
  • 本文由 发表于 2023年2月24日 17:10:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定