Path: blob/master/AugmentedRealityWithArucoMarkers/augmented_reality_with_aruco.py
3092 views
# This code is written by Sunita Nayak at BigVision LLC. It is based on the OpenCV project. It is subject to the license terms in the LICENSE file found in this distribution and at http://opencv.org/license.html12# Usage example: python3 augmented_reality_with_aruco.py --image=test.jpg3# python3 augmented_reality_with_aruco.py --video=test.mp445import cv2 as cv6#from cv2 import aruco7import argparse8import sys9import os.path10import numpy as np1112parser = argparse.ArgumentParser(description='Augmented Reality using Aruco markers in OpenCV')13parser.add_argument('--image', help='Path to image file.')14parser.add_argument('--video', help='Path to video file.')15args = parser.parse_args()1617im_src = cv.imread("new_scenery.jpg");1819outputFile = "ar_out_py.avi"20if (args.image):21# Open the image file22if not os.path.isfile(args.image):23print("Input image file ", args.image, " doesn't exist")24sys.exit(1)25cap = cv.VideoCapture(args.image)26outputFile = args.image[:-4]+'_ar_out_py.jpg'27elif (args.video):28# Open the video file29if not os.path.isfile(args.video):30print("Input video file ", args.video, " doesn't exist")31sys.exit(1)32cap = cv.VideoCapture(args.video)33outputFile = args.video[:-4]+'_ar_out_py.avi'34print("Storing it as :", outputFile)35else:36# Webcam input37cap = cv.VideoCapture(0)3839# Get the video writer initialized to save the output video40if (not args.image):41vid_writer = cv.VideoWriter(outputFile, cv.VideoWriter_fourcc('M','J','P','G'), 28, (round(2*cap.get(cv.CAP_PROP_FRAME_WIDTH)),round(cap.get(cv.CAP_PROP_FRAME_HEIGHT))))4243winName = "Augmented Reality using Aruco markers in OpenCV"4445while cv.waitKey(1) < 0:46try:47# get frame from the video48hasFrame, frame = cap.read()4950# Stop the program if reached end of video51if not hasFrame:52print("Done processing !!!")53print("Output file is stored as ", outputFile)54cv.waitKey(3000)55break5657#Load the dictionary that was used to generate the markers.58dictionary = cv.aruco.Dictionary_get(cv.aruco.DICT_6X6_250)5960# Initialize the detector parameters using default values61parameters = cv.aruco.DetectorParameters_create()6263# Detect the markers in the image64markerCorners, markerIds, rejectedCandidates = cv.aruco.detectMarkers(frame, dictionary, parameters=parameters)6566index = np.squeeze(np.where(markerIds==25));67refPt1 = np.squeeze(markerCorners[index[0]])[1];6869index = np.squeeze(np.where(markerIds==33));70refPt2 = np.squeeze(markerCorners[index[0]])[2];7172distance = np.linalg.norm(refPt1-refPt2);7374scalingFac = 0.02;75pts_dst = [[refPt1[0] - round(scalingFac*distance), refPt1[1] - round(scalingFac*distance)]];76pts_dst = pts_dst + [[refPt2[0] + round(scalingFac*distance), refPt2[1] - round(scalingFac*distance)]];7778index = np.squeeze(np.where(markerIds==30));79refPt3 = np.squeeze(markerCorners[index[0]])[0];80pts_dst = pts_dst + [[refPt3[0] + round(scalingFac*distance), refPt3[1] + round(scalingFac*distance)]];8182index = np.squeeze(np.where(markerIds==23));83refPt4 = np.squeeze(markerCorners[index[0]])[0];84pts_dst = pts_dst + [[refPt4[0] - round(scalingFac*distance), refPt4[1] + round(scalingFac*distance)]];8586pts_src = [[0,0], [im_src.shape[1], 0], [im_src.shape[1], im_src.shape[0]], [0, im_src.shape[0]]];8788pts_src_m = np.asarray(pts_src)89pts_dst_m = np.asarray(pts_dst)9091# Calculate Homography92h, status = cv.findHomography(pts_src_m, pts_dst_m)9394# Warp source image to destination based on homography95warped_image = cv.warpPerspective(im_src, h, (frame.shape[1],frame.shape[0]))9697# Prepare a mask representing region to copy from the warped image into the original frame.98mask = np.zeros([frame.shape[0], frame.shape[1]], dtype=np.uint8);99cv.fillConvexPoly(mask, np.int32([pts_dst_m]), (255, 255, 255), cv.LINE_AA);100101# Erode the mask to not copy the boundary effects from the warping102element = cv.getStructuringElement(cv.MORPH_RECT, (3,3));103mask = cv.erode(mask, element, iterations=3);104105# Copy the mask into 3 channels.106warped_image = warped_image.astype(float)107mask3 = np.zeros_like(warped_image)108for i in range(0, 3):109mask3[:,:,i] = mask/255110111# Copy the warped image into the original frame in the mask region.112warped_image_masked = cv.multiply(warped_image, mask3)113frame_masked = cv.multiply(frame.astype(float), 1-mask3)114im_out = cv.add(warped_image_masked, frame_masked)115116# Showing the original image and the new output image side by side117concatenatedOutput = cv.hconcat([frame.astype(float), im_out]);118cv.imshow("AR using Aruco markers", concatenatedOutput.astype(np.uint8))119120# Write the frame with the detection boxes121if (args.image):122cv.imwrite(outputFile, concatenatedOutput.astype(np.uint8));123else:124vid_writer.write(concatenatedOutput.astype(np.uint8))125126127except Exception as inst:128print(inst)129130cv.destroyAllWindows()131if 'vid_writer' in locals():132vid_writer.release()133print('Video writer released..')134135136