英文:
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? 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()
阈值图像:
结果图像:
英文:
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:
Input 2:
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:
Result Image:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论