[OpenCV] Python 에서 C++ DLL 사용하기
OpenCV 2026. 2. 19. 11:08 |Python에서 로드한 OpenCV 데이터를 C++ DLL 함수로 처리해 보자.
C++ DLL 프로젝트를 만들고 OpenCV 라이브러리를 설정한 후 아래 코드를 빌드하고 DLL 파일을 만든다.
<Dll.h>
#pragma once
#include "opencv2/opencv.hpp"
extern "C" __declspec(dllexport) void cvt(uchar* srcData, int width, int height, int channels, int type);
<Dll.cpp>
#include "DllHeader.h"
extern "C" __declspec(dllexport) void cvt(uchar* srcData, int width, int height, int channels, int type)
{
cv::Mat temp(height, width, type); // height, width, type 순이다.
// Mat의 형식이 항상 일정하다면 temp를 전역 변수로 선언해 두고 사용하는게 효율적.
temp.data = srcData; // 이미지 정보 포인터 변경.
// 만약 temp를 전역변수로 둔다면 width, height, channels, type 정보도 필요 없다.
cv::cvtColor(temp, temp, cv::COLOR_BGR2RGB); // 컬러 순서 변경.
}
위 DLL 프로젝트를 빌드하고 생성된 DLL 파일을 파이썬 프로젝트에 넣는다.
<Python.py>
import cv2
import ctypes
import sys
clib = ctypes.windll.LoadLibrary('./Dll.dll')
# Dll.dll이 C++ OpenCV를 사용하므로 opencv_worldXXX.dll파일도 프로젝트 디렉토리에 있어야 한다.
cvt = clib.cvt # dll에 있는 cvt 함수
cvt.argtypes = (ctypes.POINTER(ctypes.c_ubyte), ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int) # cvt함수의 인수 타입 지정
cvt.restype = None # void 반환을 명시
image = cv2.imread("catsdogs.png")
height, width, channels = image.shape
if image.dtype == 'uint8' and image.flags['C_CONTIGUOUS'] == True:
if channels == 1:
image_type = cv2.CV_8UC1
elif channels == 3:
image_type = cv2.CV_8UC3
elif channels == 4:
image_type = cv2.CV_8UC4
else:
print("Image type is not uint8 or C_CONTIGUOUS")
sys.exit(1)
#C_CONTIGUOUS: The data is in a single, C-style contiguous segment.
#https://numpy.org/doc/1.25/reference/generated/numpy.ndarray.flags.html
#print(image.flags)
#print(image.flags['C_CONTIGUOUS'])
data_pointer_as_c_char = ctypes.cast(image.ctypes.data, ctypes.POINTER(ctypes.c_ubyte))
# image.ctypes.data: 이미지의 데이터 위치를 가리키는 포인터
# c타입으로 포인터 변환.
cvt(data_pointer_as_c_char, width, height, channels, image_type)
# C dll에 있는 함수를 이용해 컬러 순서 변경.
cv2.imshow("image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
2023.12.17 - [Python] - Python C/C++ Library Wrapper 파이썬 C/C++ 라이브러리 연동

※ 참고
2026.02.18 - [OpenCV] - [OpenCV] C# 에서 C++ DLL 사용하기
2025.02.16 - [OpenCV] - C# and Python OpenCV Image Data Share (Memory Mapped File)
2025.02.23 - [OpenCV] - C and Python OpenCV Image Data Share (Memory Mapped File)
'OpenCV' 카테고리의 다른 글
| [OpenCV] C# 에서 C++ DLL 사용하기 (0) | 2026.02.18 |
|---|---|
| [OpenCV] Device(Camera) Enumerator 카메라 구분하기 (0) | 2026.02.16 |
| [OpenCV] Desktop Capture 화면 캡쳐 (0) | 2026.02.11 |
| OpenCV Contour Nozzle Dripping Detection (0) | 2025.04.29 |
| IP Camera ONVIF Protocol (0) | 2025.03.01 |








