OpenCV Python将一张图片粘贴到另一张图片上
时间: 2023-09-13 14:09:43 浏览: 1522
您好!要将一张图片粘贴到另一张图片上,可以使用以下步骤:
1. 使用 OpenCV 读取源图像和目标图像。
```python
import cv2
src_img = cv2.imread('source_image.jpg')
dst_img = cv2.imread('destination_image.jpg')
```
2. 确定源图像要粘贴到目标图像的位置。
```python
# 粘贴位置左上角的坐标
x_offset = 100
y_offset = 100
# 粘贴位置的宽度和高度
width = src_img.shape[1]
height = src_img.shape[0]
```
3. 使用 OpenCV 的 `cv2.resize()` 函数将源图像的大小调整为与粘贴位置的大小相同。
```python
# 调整源图像的大小
resized_src_img = cv2.resize(src_img, (width, height))
```
4. 使用 OpenCV 的 `cv2.addWeighted()` 函数将源图像叠加到目标图像的指定位置上。
```python
# 将源图像叠加到目标图像的指定位置上
dst_img[y_offset:y_offset+height, x_offset:x_offset+width] = cv2.addWeighted(resized_src_img, 1, dst_img[y_offset:y_offset+height, x_offset:x_offset+width], 0, 0)
```
完整代码如下:
```python
import cv2
# 读取源图像和目标图像
src_img = cv2.imread('source_image.jpg')
dst_img = cv2.imread('destination_image.jpg')
# 确定源图像要粘贴到目标图像的位置
x_offset = 100
y_offset = 100
width = src_img.shape[1]
height = src_img.shape[0]
# 调整源图像的大小
resized_src_img = cv2.resize(src_img, (width, height))
# 将源图像叠加到目标图像的指定位置上
dst_img[y_offset:y_offset+height, x_offset:x_offset+width] = cv2.addWeighted(resized_src_img, 1, dst_img[y_offset:y_offset+height, x_offset:x_offset+width], 0, 0)
# 显示结果
cv2.imshow('Result', dst_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
注意:在将源图像叠加到目标图像的指定位置上时,需要确保两张图片的大小和粘贴位置的大小相同,否则可能会出现意想不到的结果。
阅读全文
相关推荐


















