繁体   English   中英

图像叠加 Python OpenCV

[英]Image Overlay Python OpenCV

我正在尝试将图像叠加到另一个图像上,类似于水印。 它适用于测试徽标,但是当我使用实际徽标尝试时,出现错误:

Traceback (most recent call last):
  File "C:/Users/dv/PycharmProjects/Image/main.py", line 28, in <module>
    result = cv2.addWeighted(roi, 1, logo, 0.3, 0)
cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-_8k9tw8n\opencv\modules\core\src\arithm.cpp:650: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and the same number of channels), nor 'array op scalar', nor 'scalar op array' in function 'cv::arithm_op'

大小看起来一样,所以我不确定它指的是什么。 例如,如果我使用这个标志运行代码,

标识

上图:

图片

它显示得很好:

输出

但是当我使用这个标志时:

错误标志

它给出了上述错误。

代码:

import cv2
import numpy as np
import glob
import os

logo = cv2.imread("mylogo.png")
h_logo, w_logo, _ = logo.shape

images_path = glob.glob("images/*.*")

print("Adding watermark")
for img_path in images_path:
    img = cv2.imread(img_path)
    h_img, w_img, _ = img.shape

    # Get the center of the original. It's the location where we will place the watermark
    center_y = int(h_img / 2)
    center_x = int(w_img / 2)
    top_y = center_y - int(h_logo / 2)
    left_x = center_x - int(w_logo / 2)
    bottom_y = top_y + h_logo
    right_x = left_x + w_logo

    # Get ROI
    roi = img[top_y: bottom_y, left_x: right_x]

    # Add the Logo to the Roi
    result = cv2.addWeighted(roi, 1, logo, 0.3, 0)

    # Replace the ROI on the image
    img[top_y: bottom_y, left_x: right_x] = result

    # Get filename and save the image
    filename = os.path.basename(img_path)
    cv2.imwrite("images/watermarked_" + filename, img)


print("Watermark added to all the images")

加载徽标后检查其大小。 您的第二个徽标似乎比您的背景图像大得多。

  • 第一个标志的尺寸: 600x156x3
  • 背景图片: 1280x1920x3

所以当你得到投资回报率时:

top_y = center_y - int(h_logo / 2) # 960 - 78 = 782
left_x = center_x - int(w_logo / 2) # 640 - 300 = 340

bottom_y = top_y + h_logo # 782 + 156 = 938
right_x = left_x + w_logo # 340 + 600 = 940

# Get ROI
roi = img[top_y: bottom_y, left_x: right_x]
# roi = img[782:938, 340:940] this is okay because img.shape=(1920, 1280, 3)

但是,当您尝试放置另一个徽标时,徽标的形状会出现错误:

  • 第二个标志的尺寸: 3544x3544x3
  • 背景图片: 1280x1920x3
top_y = center_y - int(h_logo / 2) # 960 - 1772 = -812
left_x = center_x - int(w_logo / 2) # 640 - 1772 = -1132
# from these two points it's clear that coordinate cannot be negative so you should resize the second logo

bottom_y = top_y + h_logo 
right_x = left_x + w_logo

# Get ROI
roi = img[top_y: bottom_y, left_x: right_x]
# roi = img[782:938, 340:940] this is okay because img.shape=(1920, 1280, 3)

因此,您应该在加载后调整第二个徽标的大小。 你可以放类似这样的东西:

logo = cv2.imread("secondLogo.png")
logo = cv2.resize(logo, (156, 600)
h_logo, w_logo, _ = logo.shape

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM