opencv 矩形轮廓筛选及仿射变换(背景替换)

import cv2
import numpy as np


def read_img(path,threshold):
    """
    预处理图片
    :param path:
        图片路径
    :return:
        原图,二值图像
    """
    # 读取图像
    img = cv2.imread(path)
    # 转化灰度
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 高斯模糊
    img_gray = cv2.GaussianBlur(img_gray, (3, 3), 1)
    # 二值转化
    _, img_br = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY)

    return img,img_br

def findContours(src,img_br):
    # 寻找轮廓角点
    """
    :param path:
        原图路径
    :return:
        轮廓坐标,type->ndarray,shape->4,2
    """
    # 寻找外层轮廓
    contours, hierarchy = cv2.findContours(img_br, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 确保至少找到一个轮廓
    contour = np.zeros((4, 2))
    if len(contours) > 0:
        # 按轮廓大小降序排列
        cnts = sorted(contours, key=cv2.contourArea, reverse=True)
        for c in cnts:
            # 近似轮廓
            peri = cv2.arcLength(c, True)
            approx = cv2.approxPolyDP(c, 0.02 * peri, True)
            # 近似轮廓有四个点,则确定
            if len(approx) == 4:
                contour = approx
                break

    # 保留轮廓图片
    img_contour = src.copy()
    cv2.drawContours(img_contour, [contour], 0, (0, 0, 255), 1)
    cv2.imwrite("./contour.png",img_contour)

    return contour.reshape(4,2)



def affine_transform(src,dst,contour):
    """
    :param src:
        原图像,ndarray
    :param dst:
        子图像,ndarray
    :param contour:
        轮廓,shape->4,2
    :return:
        result
    """

    # 初始化原图Mask
    mask = np.zeros_like(src)
    # 获取子图长宽,赋给mask
    h, w, c = dst.shape
    mask[:h, :w, :] = 255
    # mask 透射变换

    # 得到变换矩阵
    # 初始mask点
    point1 = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]])
    # 目标mask点
    point2 = np.float32(contour.reshape(4, 2))
    # 得到变换矩阵
    perspective_matrix = cv2.getPerspectiveTransform(point1, point2)

    # 得到里白外黑mask
    mask_center_true = cv2.warpPerspective(mask, perspective_matrix, (src.shape[1], src.shape[0]))
    # 保存
    cv2.imwrite("./mask_cneter_true.png",mask_center_true)

    # 取图
    mask_center_roi = cv2.bitwise_and(src,mask_center_true)
    cv2.imwrite("./mask_center_roi.png",mask_center_roi)

    # 反取mask
    temp = np.ones_like(src) * 255
    mask_center_false = cv2.bitwise_xor(mask_center_true,temp)
    # 保存查看
    cv2.imwrite("./mask_center_false.png",mask_center_false)

    # and
    print(type(src))
    print(type(mask_center_false))

    print(mask_center_false)
    src_center_false = cv2.bitwise_and(src,mask_center_false)
    cv2.imwrite("./src_center_false.png",src_center_false)

    # 得到dst透射变换
    temp = np.zeros_like(src)
    temp[:h,:w,:] = dst
    dst_center_true = cv2.warpPerspective(temp, perspective_matrix, (src.shape[1], src.shape[0]))

    cv2.imwrite("./dst_center_true.png",dst_center_true)

    # 融合
    result = cv2.bitwise_or(src_center_false,dst_center_true)

    return  result


if __name__ == "__main__":
    # 读取图片
    src,img_br = read_img("./src.jpg",80)
    # 查找contour
    contour = findContours(src,img_br)
    # 读取目标图片
    dst = cv2.imread("./dst.jpg")
    # 获取融合图片
    result = affine_transform(src,dst,contour)

    cv2.imshow("result",result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()




dst

src

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值