Python Opencv实践 - 简单的AR项目

        这个简单的AR项目效果是,通过给定一张静态图片作为要视频中要替换的目标物品,当在视频中检测到图片中的物体时,通过单应矩阵做投影,将视频中的物体替换成一段视频播放。这个项目的所有素材来自自己的手机拍的视频。

        静态图片:

        
        当我在原视频中检测到这本书时,会将书替换成另一个视频里的内容。

        关于opencv里的透视投影,单应矩阵等概念,请自行百度。下面是代码:

import cv2 as cv
import numpy as np

videoOriginal = cv.VideoCapture("../../SampleVideos/NationalGeography.mp4")
videoReplace = cv.VideoCapture("../../SampleVideos/Milo1.mp4")
targetImg = cv.imread("./book.png", cv.IMREAD_COLOR)
targetH,targetW,targetC = targetImg.shape

#创建ORB对象
orb = cv.ORB_create(nfeatures=1500)
#提取ORB关键点和特征描述符
kpImg,descsImg = orb.detectAndCompute(targetImg, None)
#调试:绘制关键点
#imgDebug = cv.drawKeypoints(targetImg, kpImg, None)
#cv.imshow("ORB Keypoints", imgDebug)
#匹配距离阈值
matchDistanceThr = 0.75

while True:
    ret,frame = videoOriginal.read()
    if ret == False:
        break;
    #frameAug表示最终合成的增强现实的结果图片
    frameAug = frame.copy()

    
    ret,frameReplace = videoReplace.read()
    if ret == False:
        break;
    #将视频大小调整到和待替换目标图片大小
    frameReplace = cv.resize(frameReplace, (targetW,targetH), interpolation=cv.INTER_AREA)
    
    kpVideo,descsVideo = orb.detectAndCompute(frame, None)
    #frame = cv.drawKeypoints(frame, kpVideo, None)
    #进行特征匹配
    bf = cv.BFMatcher()
    matches = bf.knnMatch(descsImg, descsVideo, k=2)
    goodMatches = []
    for m,n in matches:
        if m.distance < matchDistanceThr * n.distance:
            goodMatches.append(m)
    #print(len(goodMatches))
    #调试:绘制匹配结果
    imgFeatureMatching = cv.drawMatches(targetImg, kpImg, frame, kpVideo, goodMatches, None, flags=2)

    #找到单应矩阵
    #首先找到srcPts和dstPts
    if (len(goodMatches) > 20):
        srcPts = np.float32([kpImg[m.queryIdx].pt for m in goodMatches]).reshape(-1,1,2)
        dstPts = np.float32([kpVideo[m.trainIdx].pt for m in goodMatches]).reshape(-1,1,2)
        #找到单应矩阵
        matrix,mask = cv.findHomography(srcPts, dstPts, cv.RANSAC, 5)
        #print(matrix)
        #映射targetImg的四个角点到目标平面
        targetPts = np.float32([[0,0],[0,targetH],[targetW,targetH],[targetW, 0]]).reshape(-1,1,2)
        targetOnVideoPts = cv.perspectiveTransform(targetPts, matrix)
        #print("Target shape:", targetImg.shape)
        #print("Frame shape:", frame.shape)
        #print(targetPts)
        #print('maps to:')
        #print(targetOnVideoPts)
        #print()
        #绘制待替换目标图像的位置映射到视频帧后的边框结果
        imgTargetOnVideoBox = cv.polylines(frame, [np.int32(targetOnVideoPts)], True, (255,0,255), 3)
        #调用warpPerspective将要替换的视频文件帧图像投影到视频帧的图像
        imgWarp = cv.warpPerspective(frameReplace, matrix, (frame.shape[1],frame.shape[0]))

        #获得掩码图
        #首先将视频帧中要替换的区域内容的mask标记为全1(白色)
        maskForReplace = np.zeros((frame.shape[0],frame.shape[1]), np.uint8)
        cv.fillPoly(maskForReplace, [np.int32(targetOnVideoPts)], (255,255,255))
        #获得原视频帧内容的mask,将maskForReplace取反即可
        maskForVideo = cv.bitwise_not(maskForReplace)
        #生成增强现实的帧
        frameAug = cv.bitwise_and(frameAug, frameAug, mask = maskForVideo)
        frameAug = cv.bitwise_or(imgWarp, frameAug)

    cv.imshow('Augmented Video', frameAug)
    cv.moveWindow('Augmented Video',  imgFeatureMatching.shape[1],0)
    cv.imshow('FeatureMatchResult', imgFeatureMatching)
    cv.moveWindow('FeatureMatchResult', 0,0)
    #cv.imshow('Mask For Video', maskForVideo)
    #cv.imshow('Mask For Replace', maskForReplace)
    #cv.imshow('WarpImage', imgWarp)
    #cv.moveWindow("WarpImage", 800,0)
    #cv.imshow('TargetOnVideo', imgTargetOnVideoBox)
    
    #cv.imshow('VideoPlayer', frame)
    if cv.waitKey(33) & 0xFF == ord('q'):
        break;

videoOriginal.release()
videoReplace.release()
cv.destroyAllWindows()

        运行结果:

Python Opencv实践简单的AR项目

  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
安装方法可以通过以下步骤进行: 1. 首先,你可以尝试从清华大学的镜像站点下载opencv-pythonopencv-contrib-python。你可以使用以下链接进行下载:opencv-python https://pypi.tuna.tsinghua.edu.cn/simple/opencv-python/ opencv-python-contrib https://pypi.tuna.tsinghua.edu.cn/simple/opencv-contrib-python/ \[1\] 2. 如果以上方法不可行,你可以访问UCI的网站,找到OpenCV模块,并根据你的Python版本和CPU位数选择相应的安装包进行下载。例如,如果你的Python版本是3.9,CPU是64位,你可以选择下载opencv_python-4.5.5-cp39-cp39-win_amd64.whl文件。下载完成后,将该压缩包剪切到你的Scripts文件夹中。然后,在命令提示符中进入Python安装路径的Scripts文件夹,并使用pip命令进行安装。例如,在Python安装路径的Scripts下输入以下命令:pip3.9.exe install D:\python\Scripts\opencv_python-4.5.5-cp39-cp39-win_amd64.whl \[2\] 3. 安装完成后,你可以使用import cv2和import numpy等语句导入opencv和numpy库,并使用相应的函数进行图像处理。例如,你可以使用cv2.imread函数读取图像,并使用img.shape打印图像的形状。\[3\] #### 引用[.reference_title] - *1* *3* [python 38 安装 opencv-python 4.5.5和opencv-python-contrib 4.5.5.62](https://blog.csdn.net/weixin_42888638/article/details/123289881)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [最新openCV-Python安装教程(python:3.9||opencv-python:4.5.5)](https://blog.csdn.net/weixin_43349916/article/details/123232335)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亦枫Leonlew

希望这篇文章能帮到你

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值