본문 바로가기
OpenCV

[C++] OpenCV DNN 알고리즘으로 객체 인식/분류하는 예제 [04]

by dev_drive 2023. 3. 13.
반응형

 

 

[C++] OpenCV DNN 알고리즘으로 얼굴 인식하는 예제 [03]

[C++] OpenCV Haar Cascade로 얼굴, 눈 영역 찾기 예제 [02] [C++] OpenCV란? 개념과 설치/세팅 방법 [01] ※ OpenCV란? OpenCV는 Open Source Computer Vision Library로, 이미지와 동영상 처리에 사용되는 라이브러리 입니다

dev-drive.tistory.com

DNN 알고리즘에 대한 자세한 내용은 이전 글을 참고해주세요.

 


※ DNN 알고리즘이 적용된 Caffe 모델 다운로드

 

GitHub - PINTO0309/MobileNet-SSD-RealSense: [High Performance / MAX 30 FPS] RaspberryPi3(RaspberryPi/Raspbian Stretch) or Ubuntu

[High Performance / MAX 30 FPS] RaspberryPi3(RaspberryPi/Raspbian Stretch) or Ubuntu + Multi Neural Compute Stick(NCS/NCS2) + RealSense D435(or USB Camera or PiCamera) + MobileNet-SSD(MobileNetSSD)...

github.com

간단하게 적용해볼 수 있는 모델이라서 예제는 해당 모델로 진행하겠습니다.

 

 

 

 

 

OpenCV DNN Caffe모델로 객체 인식/분류하는 예제

 

※ 예제를 실행하기 전에 개발세팅이 되어 있지 않다면 아래 글을 참고하여 세팅 먼저 진행해주세요.

 

[C++] OpenCV란? 개념과 설치/세팅 방법 [01]

※ OpenCV란? OpenCV는 Open Source Computer Vision Library 약자로, 이미지와 동영상 처리에 사용되는 라이브러리 입니다. C++, Python, Java 등 다양한 프로그래밍 언어를 지원하며 이미지 프로세싱, 컴퓨터 비전

dev-drive.tistory.com

 

#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;
using namespace cv::dnn;


string CLASSES[] = { "background", "aeroplane", "bicycle", "bird", "boat",
	"bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
	"dog", "horse", "motorbike", "person", "pottedplant", "sheep",
	"sofa", "train", "tvmonitor" };
    
// 입력 이미지 불러오기
Mat img = imread("test2.jpg");

// 딥러닝 모델 불러오기
Net net = readNetFromCaffe("MobileNetSSD_deploy.prototxt.txt", "MobileNetSSD_deploy.caffemodel");

// 객체 검출 수행
Mat blob = blobFromImage(img, 0.007843, Size(300, 300), Scalar(127.5, 127.5, 127.5));
net.setInput(blob);
Mat detection = net.forward();

// 검출된 객체 정보 출력
Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
for (int i = 0; i < detectionMat.rows; i++)
{
	float confidence = detectionMat.at<float>(i, 2);
	if (confidence > 0.4)
	{
		int class_id = (int)(detectionMat.at<float>(i, 1));
		int x1 = static_cast<int>(detectionMat.at<float>(i, 3) * img.cols);
		int y1 = static_cast<int>(detectionMat.at<float>(i, 4) * img.rows);
		int x2 = static_cast<int>(detectionMat.at<float>(i, 5) * img.cols);
		int y2 = static_cast<int>(detectionMat.at<float>(i, 6) * img.rows);
        
		// 검출된 객체 위치 표시
		rectangle(img, Point(x1, y1), Point(x2, y2), Scalar(0, 255, 0), 2);
        
		// 검출된 객체 분류 및 정확도 표시
		String label = format("%s: %.2f", CLASSES[class_id].c_str(), confidence);
		int baseline;
		Size label_size = getTextSize(label, FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseline);
		rectangle(img, Point(x1, y1 - label_size.height), Point(x1 + label_size.width, y1), Scalar(0, 255, 0), -1);
		putText(img, label, Point(x1, y1), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 0, 0), 1);
	}
}

// 결과 이미지 출력
imshow("result", img);
waitKey(0);

이미지 출처=unsplash

 

해당 모델은 분류할 수 있는 객체가 20가지이고 정확도가 많이 높지는 않습니다.

간단히 이런식으로 사용한다는 정도만 알아두시고 더 깊게 공부하고 싶으시면 

PyTorch의 YOLO 등 꾸준히 학습하고 업데이트되는 모델들을 찾아서 활용해보시길 바랍니다.

 

YOLO모델은 버전이 다양하게 있으며 더 높은 정확도와 80~90가지 정도의 객체를 분류할 수 있고,

인물의 감정 인식, 나이와 성별 추측 등도 가능합니다.

 

반응형

댓글