이미지 파일 읽기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat image1(300400, CV_8U, Scalar(255));
    Mat image2(300400, CV_8U, Scalar(100));
    string  title1 = "white창 제어";
    string  title2 = "gray 창 제어";
 
    namedWindow(title1, WINDOW_AUTOSIZE);
    namedWindow(title2, WINDOW_NORMAL);
    moveWindow(title1, 100200);
    moveWindow(title2, 300200);
 
    imshow(title1, image1);
    imshow(title2, image2);
    waitKey();
    destroyAllWindows();
 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

비디오 파일 읽기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
 
void put_string(Mat &frame, string text, Point pt, int value)
{
    text += to_string(value);
    Point shade = pt + Point(22);
    int font = FONT_HERSHEY_PLAIN;
    putText(frame, text, shade, font, 1.8, Scalar(000), 2);
    putText(frame, text, pt, font, 1.8, Scalar(12020090), 2);
}
 
int main()
{
    VideoCapture capture;
    capture.open("./image/move_file.avi");
    CV_Assert(capture.isOpened());
 
    double frame_rate = capture.get(CAP_PROP_FPS);
    int delay = 1000 / frame_rate;
    int frmae_cnt = 0;
    Mat  frame;
 
    while (capture.read(frame))
    {
        if (waitKey(delay) >= 0break;
 
        if (frmae_cnt < 100);
        else if (frmae_cnt < 200)    frame -= Scalar(00100);
        else if (frmae_cnt < 300)     frame += Scalar(10000);
        else if (frmae_cnt < 400)    frame = frame * 1.5;
        else if (frmae_cnt < 500)    frame = frame * 0.5;
 
        put_string(frame, "frmae_cnt ", Point(2050), frmae_cnt++);
        imshow("동영상 파일읽기", frame);
    }
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

채널 처리 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat image = imread("./image/color.jpg", IMREAD_COLOR);
    CV_Assert(image.data);
 
    Mat bgr[3];
    split(image, bgr);
 
    imshow("image", image);
    imshow("blue 채널", bgr[0]);
    imshow("green 채널", bgr[1]);
    imshow("red 채널", bgr[2]);
 
    waitKey(0);
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

논리/비트/연산 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat image = imread("./image/bit_test.jpg", IMREAD_COLOR);
    Mat logo = imread("./image/logo.jpg", IMREAD_COLOR);
    CV_Assert(image.data && logo.data);            // 예외처리
    Mat logo_th, masks[5], background, foreground, dst;        // 결과 행렬
    
    threshold(logo, logo_th, 70255, THRESH_BINARY); // 로고 영상 이진화
    split(logo_th, masks);                        // 로고영상 채널 분리
 
    bitwise_or(masks[0], masks[1], masks[3]);    // 전경통과 마스크
    bitwise_or(masks[2], masks[3], masks[3]);
    bitwise_not(masks[3], masks[4]);            // 배경통과 마스크
 
    Point center1 = image.size()/ 2;            // 영상 중심좌표
    Point center2 = logo.size() / 2;;            // 로고 중심좌표
    Point start = center1 - center2;
    Rect roi(start, logo.size());                // 로고가 위치할 관심영역
 
    //비트곱과 마스킹을 이용한 관심 영역의 복사
    bitwise_and(logo, logo, foreground, masks[3]);
    bitwise_and(image(roi), image(roi), background, masks[4]);
 
    add(background, foreground, dst);            // 로고 전경과 배경 합성
    dst.copyTo(image(roi));                        // 로고 합성 영상을 관심영역에 복사
 
    imshow("background", background);
    imshow("foreground", foreground);
    imshow("dst", dst);
    imshow("image", image);
    waitKey();
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

원소의 절댓값

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat image1 = imread("./image/abs_test1.jpg"0);
    Mat image2 = imread("./image/abs_test2.jpg"0);
    CV_Assert(image1.data && image2.data);
 
    Mat dif_img, abs_dif1, abs_dif2;
 
    image1.convertTo(image1, CV_16S);
    image2.convertTo(image2, CV_16S);
    subtract(image1, image2, dif_img);
 
    Rect roi(101073);
    cout << "[dif_img] = " << endl << dif_img(roi) << endl;
 
    abs_dif1 = abs(dif_img);
 
    image1.convertTo(image1, CV_8U);
    image2.convertTo(image2, CV_8U);
    dif_img.convertTo(dif_img, CV_8U);
    abs_dif1.convertTo(abs_dif1, CV_8U);
 
    absdiff(image1, image2, abs_dif2);
 
    cout << "[dif_img] = " << endl << dif_img(roi) << endl << endl;
    cout << "[abs_dif1] = " << endl << abs_dif1(roi) << endl;
    cout << "[abs_dif2] = " << endl << abs_dif2(roi) << endl;
 
    imshow("image1", image1);
    imshow("image2", image2);
    imshow("dif_img", dif_img);
    imshow("abs_dif1", abs_dif1);
    imshow("abs_dif2", abs_dif2);
    waitKey();
    return 0;
 
    
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

그레이 스케일 영상

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat  m1(35, CV_32SC1);
    Mat  m2(35, CV_32FC1);
    Mat  m3(35, CV_8UC2);
    Mat  m4(35, CV_32SC3);
 
    for (int i = 0, k = 0; i < m1.rows; i++){
        for (int j = 0; j < m1.cols; j++, k++)
        {
            m1.at<int>(i, j) = k;
            Point pt(j, i);
            m2.at<float>(pt) = (float)j;
 
            int idx[2= { i, j };
            m3.at<Vec2b>(idx) = Vec2b(01);
 
            m4.at<Vec3i>(i, j)[0= 0;
            m4.at<Vec3i>(i, j)[1= 1;
            m4.at<Vec3i>(i, j)[2= 2;
        }
    }
    cout << "[m1] = " << endl << m1 << endl;
    cout << "[m2] = " << endl << m2 << endl;
    cout << "[m3] = " << endl << m3 << endl;
    cout << "[m4] = " << endl << m4 << endl;
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

 

영상 밝기의 가감연산

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
    Mat image = imread("./image/bright.jpg", IMREAD_GRAYSCALE);
    CV_Assert(!image.empty());
 
    Mat dst1 = image + 100;
    Mat dst2 = image - 100;
    Mat dst3 = 255 - image;
 
    Mat dst4(image.size(), image.type());
    Mat dst5(image.size(), image.type());
 
    for (int i = 0; i < image.rows; i++){
        for (int j = 0; j < image.cols; j++)
        {
            dst4.at<uchar>(i, j) = image.at<uchar>(i, j) + 100;
            dst5.at<uchar>(i, j) = 255 - image.at<uchar>(i, j);
        }
    }
 
    imshow("원 영상", image);
    imshow("dst1 - 밝게", dst1);
    imshow("dst2 - 어둡게", dst2);
    imshow("dst3 - 반전", dst3);
    imshow("dst4 - 밝게", dst4);
    imshow("dst5 - 반전", dst5);
    waitKey();
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

OpenCV 함수 활용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
 
void  calc_Histo(const Mat& image, Mat& hist, int bins, int range_max = 256)
{
    int        histSize[] = { bins };            // 히스토그램 계급개수
    float   range[] = { 0, (float)range_max };        // 히스토그램 범위
    int        channels[] = { 0 };                // 채널 목록
    const float* ranges[] = { range };
 
    calcHist(&image, 1, channels, Mat(), hist, 1, histSize, ranges);
}
 
void draw_histo(Mat hist, Mat &hist_img, Size size = Size(256200))
{
    hist_img = Mat(size, CV_8U, Scalar(255));
    float  bin = (float)hist_img.cols / hist.rows;
    normalize(hist, hist, 0size.height, NORM_MINMAX);
 
    for (int i = 0; i<hist.rows; i++)
    {
        float  start_x = (i * bin);
        float  end_x = (i + 1* bin;
        Point2f pt1(start_x, 0);
        Point2f pt2(end_x, hist.at <float>(i));
 
        if (pt2.y > 0)
            rectangle(hist_img, pt1, pt2, Scalar(0), -1);
    }
    flip(hist_img, hist_img, 0);
}
 
 
 
int main()
{
    Mat image = imread("./image/pixel_test.jpg", IMREAD_GRAYSCALE);
    CV_Assert(!image.empty());
 
    Mat hist, hist_img;
    calc_Histo(image, hist, 256);
    draw_histo(hist, hist_img);
 
    imshow("hist_img", hist_img);
    imshow("image", image);
    waitKey();
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

히스토그램 스트레칭 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
 
void  calc_Histo(const Mat& image, Mat& hist, int bins, int range_max = 256)
{
    int        histSize[] = { bins };            // 히스토그램 계급개수
    float   range[] = { 0, (float)range_max };        // 히스토그램 범위
    int        channels[] = { 0 };                // 채널 목록
    int        dims = image.channels();;
    const float* ranges[] = { range };
 
    calcHist(&image, 1, channels, Mat(), hist, 1, histSize, ranges);
}
 
// hue 채널에 대한 색상 팔레트 행렬 생성
Mat  make_palatte(int rows)
{
    Mat hsv(rows, 1, CV_8UC3);
    for (int i = 0; i < rows; i++)
    {
        uchar hue = saturate_cast<uchar>((float)i / rows * 180);
        hsv.at<Vec3b>(i) = Vec3b(hue, 255255);
    }
    cvtColor(hsv, hsv,COLOR_HSV2BGR);
    return hsv;
}
 
void draw_histo_hue(Mat hist, Mat &hist_img, Size size = Size(256200))
{
    Mat hsv_palatte = make_palatte(hist.rows);
 
    hist_img = Mat(size, CV_8UC3, Scalar(255255255));
    float  bin = (float)hist_img.cols / hist.rows;
    normalize(hist, hist, 0hist_img.rows, NORM_MINMAX);
 
    for (int i = 0; i<hist.rows; i++)
    {
        float start_x = (i * bin);
        float  end_x = (i + 1* bin;
        Point2f pt1(start_x, 0);
        Point2f pt2(end_x, hist.at <float>(i));
 
 
        Scalar color = hsv_palatte.at<Vec3b>(i);                // 색상팔레트 색지정
        if (pt2.y>0) rectangle(hist_img, pt1, pt2, color, -1);    // 팔레트 색 그리기    
    }
    flip(hist_img, hist_img, 0);
}
 
int main()
{
    Mat image = imread("./image/hue_hist.jpg", IMREAD_COLOR);
    CV_Assert(!image.empty());
 
    Mat HSV_img, HSV_arr[3];
    cvtColor(image, HSV_img, COLOR_BGR2HSV);
    split(HSV_img, HSV_arr);
 
    Mat hue_hist, hue_hist_img;
    calc_Histo(HSV_arr[0], hue_hist, 18180);// Hue 채널 히스토그램 계산
    draw_histo_hue(hue_hist, hue_hist_img, Size(360200)); // 히스토그램 그래프
 
    imshow("image", image);
    imshow("Hue_hist_img", hue_hist_img);
    waitKey();
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

차분 연산을 통한 에지 검출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
 
void homogenOp(Mat img, Mat& dst, int mask_size)
{
    dst = Mat(img.size(), CV_8U, Scalar(0));
    Point h_m(mask_size / 2, mask_size / 2);
 
    for (int i = h_m.y; i < img.rows - h_m.y; i++){
        for (int j = h_m.x; j < img.cols - h_m.x; j++)
        {
            uchar max = 0;
            for (int u = 0; u < mask_size; u++)    {
                for (int v = 0; v < mask_size; v++)
                {
                    int y = i + u - h_m.y;
                    int x = j + v - h_m.x;
                    uchar difference = abs(img.at<uchar>(i, j) - img.at<uchar>(y, x));
                    if (difference > max) max = difference;
                }
            }
            dst.at<uchar>(i, j) = max;
        }
    }
}
 
 
 
int main()
{
    Mat image = imread("./image/edge_test.jpg", IMREAD_GRAYSCALE);
    CV_Assert(image.data);
 
    Mat edge;
    homogenOp(image, edge, 3);
 
    imshow("image", image);
    imshow("edge-homogenOp", edge);
    waitKey();
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

로버츠 마스크

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
 
void filter(Mat img, Mat& dst, Mat mask)
{
    dst = Mat(img.size(), CV_32F, Scalar(0));
    Point h_m = mask.size() / 2;
 
    for (int i = h_m.y; i < img.rows - h_m.y; i++){
        for (int j = h_m.x; j < img.cols - h_m.x; j++)
        {
            float sum = 0;
            for (int u = 0; u < mask.rows; u++)    {
                for (int v = 0; v < mask.cols; v++)
                {
                    int y = i + u - h_m.y;
                    int x = j + v - h_m.x;
                    sum += img.at<uchar>(y, x) * mask.at<float>(u, v);
                }
            }
            dst.at<float>(i, j) = sum;
        }
    }
}
 
void differential(Mat image, Mat& dst, float data1[], float data2[])
{
    Mat dst1, dst2;
    Mat mask1(33, CV_32F, data1);            // 입력 인수로 마스크 행렬 초기화
    Mat mask2(33, CV_32F, data2);
 
    filter(image, dst1, mask1);                    // 사용자 정의 회선 함수
    filter(image, dst2, mask2);
    magnitude(dst1, dst2, dst);                    // 회선 결과 두 행렬의 크기 계산
    dst.convertTo(dst, CV_8U);                    // 윈도우 표시 위한 형변환
 
    dst1 = abs(dst1);                            // 회선 결과 음수 원소를 양수화    
    dst2 = abs(dst2);
    dst1.convertTo(dst1, CV_8U);                // 윈도우 표시 위한 형변환
    dst2.convertTo(dst2, CV_8U);
    imshow("dst1", dst1);
    imshow("dst2", dst2);
}
 
int main()
{
    Mat image = imread("./image/edge_test1.jpg", IMREAD_GRAYSCALE);
    CV_Assert(image.data);
 
    float data1[] = {
        -100,
        010,
        000
    };
    float data2[] = {
        00-1,
        010,
        000
    };
 
    Mat dst;
    differential(image, dst, data1, data2);
    
    imshow("image", image);
    imshow("로버츠 에지", dst);
    waitKey();
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

자동차 번호판 검출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
 
int main()
{
    while(1)
    {
        int no;
        cout << "차량 영상 번호( 0:종료 ) : ";
        cin >> no;
        if (no == 0break;
 
        string fname = format("./test_car/%02d.jpg", no);
        Mat image = imread(fname, 1); 
        if (image.empty()) {
            cout << to_string(no) + "번 영상 파일이 없습니다. " << endl;
            continue;
        }
 
        Mat gray, sobel, th_img, morph;
        Mat kernel(531, CV_8UC1, Scalar(1));        // 닫임 연산 마스크
        cvtColor(image, gray, COLOR_BGR2GRAY);        // 명암도 영상 변환
 
        blur(gray, gray, Size(55));                    // 블러링
        Sobel(gray, gray, CV_8U, 103);            // 소벨 에지 검출
 
        threshold(gray, th_img, 120255, THRESH_BINARY);    // 이진화 수행
        morphologyEx(th_img, morph, MORPH_CLOSE, kernel);    // 열림 연산 수행
 
        imshow("image", image);
        imshow("이진 영상", th_img), imshow("열림 연산", morph);
        waitKey();
    } 
    return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

+ Recent posts