OpenCV로 몰입형 증강 현실 경험을 만드는 방법
증강 현실은 재미있는 방해 요소부터 심각한 실제 모델링까지 무엇이든 제공할 수 있지만 기본부터 시작해야 합니다.
증강 현실(AR)은 실제 환경에 디지털 정보를 오버레이하여 현실과 가상 콘텐츠를 병합합니다. 최근 몇 년 동안 컴퓨터 비전과 이미지 처리 기술의 발전으로 AR 애플리케이션 개발이 더욱 쉬워졌습니다.
OpenCV는 인기 있는 오픈 소스 컴퓨터 비전 라이브러리입니다. 이는 매력적인 AR 경험을 만드는 데 도움이 되는 도구와 알고리즘을 제공합니다. AR 프로그램을 만들려면 프로젝션 이미지를 선택하고 물리적 자리 표시자 개체를 감지한 다음 AR 콘텐츠를 프로젝션하고 렌더링합니다.
환경 설정
코딩을 시작하기 전에 개발 환경을 준비해야 합니다. 가상 환경을 생성한 후 다음 터미널 명령을 실행하여 NumPy 및 OpenCV를 설치하십시오.
pip install opencv-contrib-python numpy컴퓨터 비전 기능에는 OpenCV를 사용하고 나중에 코드에서 호모그래피 행렬을 계산하려면 NumPy를 사용합니다.
opencv-python이 아닌 opencv-contrib-python 라이브러리를 설치해야 합니다. 이는 opencv-python에 증강 현실 프로그램을 생성하는 데 크게 의존하게 될 cv2.aruco 모듈이 없기 때문입니다.
전체 소스 코드는 GitHub 저장소에서 사용할 수 있습니다.
필수 라이브러리 가져오기
새 Python 파일을 만듭니다. 스크립트 시작 부분에서 OpenCV 및 NumPy를 가져옵니다.
import numpy as np
import cv2이러한 라이브러리를 가져오면 코드에서 해당 기능을 사용할 수 있습니다.
오버레이 이미지 선택
AR 장면에서 가상 객체를 렌더링할 때 애플리케이션이 감지된 마커에 투영할 이미지가 필요합니다. cv2.imread 함수를 사용하여 오버레이 이미지를 로드합니다.
overlay_image = cv2.imread('your_overlay_image.jpg')
3D 모델을 동적으로 생성하는 등 다른 방법을 사용하여 오버레이 이미지를 얻을 수 있습니다.
ArUco 마커 감지
오버레이 이미지를 선택한 후에는 이미지를 오버레이할 비디오 피드의 위치를 결정해야 합니다. ArUco 마커가 필요한 곳입니다. 이는 컴퓨터 비전 알고리즘으로 쉽게 감지할 수 있는 고유한 ID 패턴을 가진 사각형 마커입니다.
앱이 마커를 감지하면 해당 위치에 이미지를 투영하는 등의 반응을 할 수 있습니다. 다음은 ArUco 마커의 예입니다.
비디오 피드에서 ArUco 마커를 감지하는 기능을 만듭니다. 이 함수는 비디오 피드를 회색조로 변환해야 합니다. 그런 다음 마커 크기와 총 마커를 기반으로 ArUco 사전을 얻습니다. 마지막으로 피드에서 마커를 감지해야 합니다.
def findArucoMarkers(image, markerSize=6, totalMarkers=250):
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Get the Aruco dictionary based on the marker size and total markers
dictionary_key = getattr(cv2.aruco, f'DICT_{markerSize}X'
f'{markerSize}_{totalMarkers}')
aruco_dictionary = cv2.aruco.getPredefinedDictionary(dictionary_key)
# Set the Aruco detector parameters
aruco_params = cv2.aruco.DetectorParameters()
# Detect Aruco markers in the grayscale image
marker_corners, marker_ids, _ = cv2.aruco.detectMarkers(gray, aruco_dictionary,
parameters=aruco_params)
return marker_corners, marker_ids
이 함수는 감지된 마커의 모서리와 ID를 반환합니다.
오버레이 이미지를 마커에 투영하기
비디오 프레임에서 마커를 감지한 후에는 해당 마커에 오버레이 이미지를 투영해야 합니다. 이를 달성하려면 이미지와 비디오 프레임 사이의 호모그래피 행렬을 계산하는 함수를 작성하세요. 이는 오버레이 이미지를 비디오 프레임에서 감지된 ArUco 마커와 정렬하는 기하학적 변환을 설정하기 위한 것입니다.
그런 다음 호모그래피를 기반으로 오버레이 이미지를 왜곡해야 합니다. 그런 다음 마스크를 만들어 오버레이 영역을 정의하고 마지막으로 마스크된 오버레이 이미지를 비디오 프레임과 혼합합니다.
def superimposeImageOnMarkers(video_frame, aruco_markers, overlay_image,
video_width, video_height):
frame_height, frame_width = video_frame.shape[:2]
if len(aruco_markers[0]) != 0:
for i, marker_corner in enumerate(aruco_markers[0]):
marker_corners = marker_corner.reshape((4, 2)).astype(np.int32)
# Draw a polygon around the marker corners
cv2.polylines(video_frame, [marker_corners], True, (0, 255, 0), 2)
# Add marker ID as text on the top-left corner of the marker
cv2.putText(video_frame, str(aruco_markers[1][i]),
tuple(marker_corners[0]),
cv2.FONT_HERSHEY_SIMPLEX,0.5, (0, 255, 0), 2)
# Find the homography matrix to map the overlay image onto the marker
homography_matrix, _ = cv2.findHomography(
np.array([[0, 0], [video_width, 0], [video_width, video_height],
[0, video_height]], dtype="float32"), marker_corners)
# Warp the overlay image to align with the marker using homography matrix
warped_image = cv2.warpPerspective(overlay_image, homography_matrix,
(frame_width, frame_height))
# Create a mask to apply the warped image only on the marker area
mask = np.zeros((frame_height, frame_width), dtype="uint8")
cv2.fillConvexPoly(mask, marker_corners, (255, 255, 255), cv2.LINE_AA)
masked_warped_image = cv2.bitwise_and(warped_image, warped_image,
mask=mask)
# Apply the inverse mask to the video frame
masked_video_frame = cv2.bitwise_and(video_frame, video_frame,
mask=cv2.bitwise_not(mask))
# Combine the masked warped image and masked video frame
video_frame = cv2.add(masked_warped_image, masked_video_frame)
return video_frame이 함수는 감지된 ArUco 마커에 오버레이 이미지가 겹쳐진 비디오 프레임을 반환합니다.
AR 콘텐츠 렌더링
AR 콘텐츠를 렌더링하려면 마커 감지와 이미지 투영 단계를 결합하는 함수를 만듭니다. 이 기능은 지속적으로 비디오 프레임을 캡처하고 ArUco 마커를 감지해야 합니다. 그런 다음 오버레이 이미지를 마커에 겹쳐야 합니다.
def processVideoFeed(overlay_image):
# Set the dimensions of the video feed
video_height = 480
video_width = 640
# Open the video capture
video_capture = cv2.VideoCapture(0)
# Load and resize the overlay image
overlay_image = cv2.resize(overlay_image, (video_width, video_height))
while video_capture.isOpened():
# Read a frame from the video capture
ret, video_frame = video_capture.read()
if ret:
# Find Aruco markers in the video frame
aruco_markers = findArucoMarkers(video_frame, totalMarkers=100)
# Superimpose the overlay image on the markers in the video frame
video_frame = superimposeImageOnMarkers(video_frame, aruco_markers,
overlay_image, video_width,
video_height)
# Display the video frame with overlay
cv2.imshow("Camera Feed", video_frame)
# Check for 'q' key press to exit the loop
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
이 기능은 결과 비디오 프레임을 표시하여 실제 세계에 나타나는 가상 개체의 환상을 만듭니다.
프로그램을 실행하려면 processVideoFeed 함수를 실행하세요.
# Start processing the video feed
processVideoFeed(overlay_image)이 비디오에서 프로그램의 출력 예를 볼 수 있습니다.
비디오 피드의 마커는 코드에서 지정한 것과 동일한 마커 크기 및 전체 마커 속성을 가져야 합니다.
증강현실은 어디에 적용되나요?
다양한 산업과 분야에서 증강현실을 활용하여 고객 경험을 향상시킵니다. 이러한 산업에서 사용되는 AR 애플리케이션을 통해 고객은 제품이 실제 세계에서 어떻게 보일지 시각화할 수 있습니다.
기술이 실제로 작동하는 모습을 보려면 이러한 유형의 응용 프로그램에 익숙해지십시오.

