覆盖图片中指定区域

python opencv 覆盖图片中指定区域

import numpy as np
import cv2
import time


def cover_pic_area(pic_name1, bounds_info, pic_name2=None):
    """
    覆盖图片中的指定区域, 支持同时覆盖多块区域, 支持同时覆盖两张图片中同一区域
    :param pic_name1: 图片1路径
    :param pic_name2: 图片2路径
    :param bounds_info: 覆盖的坐标 [y1, y2, x1 x2] or [[y1, y2, x1 x2], [y3, y4, x3 x4], ...]
    :return:
    """
    result = False
    try:
        if not isinstance(bounds_info[0], list):
            bounds_info = [bounds_info]
        for bounds in bounds_info:
            # 创建一个纯色图片 y x
            area_pic = np.zeros((bounds[1] - bounds[0], bounds[3] - bounds[2], 3), np.uint8)
            area_pic.fill(255)
            area_pic_mask = 255 * np.ones(area_pic.shape, area_pic.dtype)
            # 覆盖区域的中心点 x y
            area_pic_center = (int((bounds[3] + bounds[2]) / 2), int((bounds[1] + bounds[0]) / 2))
            base_pic = cv2.imread(pic_name1)
            # 纯色图片覆盖指定区域
            img = cv2.seamlessClone(area_pic, base_pic, area_pic_mask, area_pic_center, cv2.NORMAL_CLONE)
            cv2.imwrite(pic_name1, img)
            if pic_name2 is not None:
                time.sleep(0.2)
                base_pic2 = cv2.imread(pic_name2)
                img2 = cv2.seamlessClone(area_pic, base_pic2, area_pic_mask, area_pic_center, cv2.NORMAL_CLONE)
                cv2.imwrite(pic_name2, img2)
                result = True
            else:
                result = True
    except Exception as e:
        print("cover pic error, message is {}".format(e))
    finally:
        return result

你可能感兴趣的:(Opencv,Python,python,opencv)