[C++] Opencv의 모든 것 (설치경로, Mat, 픽셀 접근, 선 그리기)

2020. 8. 30. 15:08C++

Opencv 설치 페이지

 

https://opencv.org/

 

OpenCV

About the author:Pau Rodríguez is a research scientist at Element AI, Montreal. He earned his Ph.D.

opencv.org

 

Releases에 들어가서 버전별로 받으면 된다.

 

Windows의 경우 windows용으로 받으면 편리.

이후 설치하면 include, lib, dll이 생성되고 경로 설정해주면 된다.

 

 

 

#include<opencv2/opencv.hpp>

 

Mat 타입 생성

 

cv::Mat image;

cv::Mat image(height, width, CV_8UC3);  // height, width의 크기의 Color 이미지 생성

 

 

 

 

Mat 각 픽셀에 접근

 

for (int y = 0; y < height; y++){

   

   uchar* pointer = image.ptr<uchar>(y);       // 이미지 각 행의 처음주소를 포인터에 전달

 

   for (int x = 0; x < width; x++){

      pointer[x * 3 + 0] = 100;          // b

      pointer[x * 3 + 1] = 150;          // g

      pointer[x * 3 + 2] = 254;          // r

   }

}

 

※ 위에서는 각 픽셀을 Set 하게끔 코드를 짰지만 같은 방식으로 Get도 가능

 

 

 

 

선(Line) 그리기

 

void cv::line(InputOutputArray, img, Point pt1, Point pt2, const Scalar & color, int thickness = 1, int lineType = LINE_8, int shift = 0)

 

 

이미지 위에 직선 세개로 삼각형 그리기 예제

#include<opencv2/opencv.hpp>


Mat image(height, width, CV_8UC3);  // height * width 크기의 RGB 이미지 생성


line(image, Point(uv[0].first, uv[0].second), Point(uv[1].first, uv[1].second), CV_RGB(255, 0, 0), 1);
line(image, Point(uv[1].first, uv[1].second), Point(uv[2].first, uv[2].second), CV_RGB(255, 0, 0), 1);
line(image, Point(uv[2].first, uv[2].second), Point(uv[0].first, uv[0].second), CV_RGB(255, 0, 0), 1);


imwrite("image.jpg", image);

 

 

 

 

이미지 출력

 

cv::imwrite("파일명.jpg", image);

 

 

 

 

이미지 ROI with Padding

 

// Create rects representing the image and the ROI

auto image_rect = cv::Rect({}, image.size());

auto roi = cv::Rect(-50, 50, 200, 100)

 

// Find intersection, i.e. valid crop region

auto intersection = image_rect & roi;

 

// Move intersection to the result coordinate space

auto inter_roi = intersection - roi.tl();

 

// Create black image and copy intersection

cv::Mat crop = cv::Mat::zeros(roi.size(), image.type());

image(intersection).copyTo(crop(inter_roi));