無縫合并兩張圖片(封面右上角添加logo)-- opencv : 進行添加logo(水印)由于使用了cv2.seamlessClone
,cv2.seamlessClone
使用了泊松克隆(Poisson Cloning),會根據周圍的顏色信息進行顏色調整,使得融合后的區域更加自然,但這也可能導致顏色發生變化。
logo 都花了,顏色也不對了。
為了保留原來的顏色
,可以使用簡單的覆蓋方法
而不是cv2.seamlessClone
。
import os
import cv2
import sys
import traceback
import numpy as np
import requests
import loggingdef get_logoUrl(logoUrl, uid):"""Download logo image from URL and save it locally.Args:- logoUrl (str): URL of the logo image.- uid (str): Unique identifier for the image.Returns:- str: File path where the logo image is saved."""end = logoUrl.split('.')[-1]content = requests.get(logoUrl).content#logger.info(os.getcwd())try:logo_name = f'logo_images/{uid}.{end}'#logger.info(logo_name)print(logo_name)#print(os.getcwd())with open(logo_name,'wb') as f:f.write(content)return logo_nameexcept:#logger.info(traceback.format_exc())print(traceback.format_exc())# return dict(code=10099, data='系統未能獲得有效結果,請稍后重試')def merge_logo2First_page(uid, logoUrl):"""Merge a logo onto the first page image, preserving transparency if present.Args:- uid (str): Unique identifier for the image.- logoUrl (str): URL of the logo image.Returns:- str: File path where the merged image is saved."""folder = 'imgs/'# 獲取 logo 圖片logo_name = get_logoUrl(logoUrl, uid)obj = cv2.imread(logo_name, cv2.IMREAD_UNCHANGED)if obj is None:raise ValueError(f"Image at path {logo_name} could not be read.")(h, w, z) = obj.shape# 固定 logo 圖片的大小obj_fixed_size = cv2.resize(obj, (round(200 * (w / h)), 200))(h, w, z) = obj_fixed_size.shape# 檢查是否存在 Alpha 通道,如果沒有則創建一個全白的 Alpha 通道if obj_fixed_size.shape[2] == 4:alpha_channel = obj_fixed_size[:, :, 3] / 255.0obj_rgb = obj_fixed_size[:, :, :3]else:alpha_channel = np.ones((obj_fixed_size.shape[0], obj_fixed_size.shape[1]), dtype=np.float32)obj_rgb = obj_fixed_size# 讀取主圖片im = cv2.imread(folder + "auto_first_page.jpg")(height, width, channels) = im.shape# 計算 logo 的放置位置(右上角)top_left_h = 100 # 距離頂部的距離top_left_w = width - w - 222 # 距離右側的距離# 邊界檢查,確保放置位置在主圖片內if top_left_h < 0:top_left_h = 0if top_left_w < 0:top_left_w = 0if top_left_h + h > height:top_left_h = height - hif top_left_w + w > width:top_left_w = width - w# 處理透明度,將有顏色的部分覆蓋到主圖片上# for c in range(0, 3):# im[top_left_h:top_left_h + h, top_left_w:top_left_w + w, c] = (# alpha_channel * obj_rgb[:, :, c] +# (1 - alpha_channel) * im[top_left_h:top_left_h + h, top_left_w:top_left_w + w, c]# )# 矩陣計算替代顯式循環:使用 NumPy 的廣播功能,將顯式循環轉換為矩陣計算,從而提高效率。im[top_left_h:top_left_h + h, top_left_w:top_left_w + w, :3] = ((alpha_channel[..., np.newaxis] * obj_rgb) +((1 - alpha_channel[..., np.newaxis]) * im[top_left_h:top_left_h + h, top_left_w:top_left_w + w, :3]))# 保存處理后的圖片save_path = 'first_page_merged_logo/'if not os.path.exists(save_path):os.makedirs(save_path)output_path = os.path.join(save_path, f"merged_{uid}.jpg")cv2.imwrite(output_path, im)return output_path, logo_name