如何在python中使用OpenCV将一张图片叠加到另一张图片上?

fcy6dtqo  于 2023-04-21  发布在  Python
关注(0)|答案(1)|浏览(175)

我试过很多方法,但就是不行。无论我怎么做,我都不能把一张图片叠加到另一张上面。

small_img = cv2.imread('blockTextures/img.png')
x_offset = 30
y_offset = 170
x_end = x_offset + small_img.shape[1]
y_end = y_offset + small_img.shape[0]
GUI[y_offset:y_end, x_offset:x_end] = small_img

图形用户界面是大的形象在这里和小的一个只是一个小块,应该有颜色等,但它只是看起来白色

5sxhfpxr

5sxhfpxr1#

我有两个选择。你需要两个图像。。一个大一点的图像,一个小一点的图像。
1.有边框的
1.一个没有边界
片段选项1:

#!/usr/bin/python37
#OpenCV 4.3.0, Raspberry pi3B/+, 4b/4g/8g, Thonny 3.7.3
#Date: 29th June, 2020

import cv2
import numpy as np

img1 = cv2.imread('ralph.jpg')
img2 = cv2.imread('mainlogo.png')

# I want to put logo on top-left corner, So I create a ROI
rows,cols,channels = img2.shape

roi = img1[0:rows, 0:cols]

# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)

# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)

# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2, img2, mask=mask)

# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg, img2_fg)
img1[450:rows+450, 450:cols+450] = dst

cv2.imshow('res', img1)
cv2.waitKey(0)
cv2.destroyAllWindows()

截图:

片段选项2:

#!/usr/bin/env python35
#OpenCV 4.3.0, Raspberry pi3B/+, 4b/4g/8g, Thonny 3.7.3
#Date: 1st July, 2020

import cv2
import numpy as np

img1 = cv2.imread('ralph.jpg')
overlay_img1 = np.ones(img1.shape,np.uint8)*255

img2 = cv2.imread('mainlogo.png')
rows,cols,channels = img2.shape
overlay_img1[450:rows+450, 450:cols+450 ] = img2

img2gray = cv2.cvtColor(overlay_img1,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray,220,55,cv2.THRESH_BINARY_INV)
mask_inv = cv2.bitwise_not(mask)
temp1 = cv2.bitwise_and(img1,img1,mask = mask_inv)
temp2 = cv2.bitwise_and(overlay_img1,overlay_img1, mask = mask)

result = cv2.add(temp1,temp2)
cv2.imshow("Result",result)
cv2.imwrite("Result.jpg",result)
cv2.waitKey(0)
cv2.destroyAllWindows()

截图:

相关问题