프로젝트/OpenCV

영상처리 알고리즘 병렬화 - [OpenCV][C++]영상에 Salt and Pepper Noise 추가

윤깡패 2023. 6. 7. 03:46

Previous Post

영상처리 알고리즘 병렬화 - [OpenCV][C++]영상 읽기/출력/저장

 

영상처리 알고리즘 병렬화 - [OpenCV][C++]영상 읽기/출력/저장

OpenCV(Open Source Computer Vision Library) : 실시간 컴퓨터 비전을 목적으로 한 라이브러리 https://opencv.org Home OpenCV provides a real-time optimized Computer Vision library, tools, and hardware. It also supports model execution for Ma

soobin0821.tistory.com

 


 

Goal

  • 원본 영상에 Salt and Pepper 노이즈 추가
  • 노이즈 추가된 영상을 출력 및 저장

 

 

Content

Salt and Pepper Noise

  : 검은색(픽셀값 0) 또는 흰색(픽셀값 255) 점의 형태로 발생하는 잡음

 

Salt and Pepper Noise 구현 함수

  • void  addNoise(Mat &image, int noise_num)

- image : 노이즈를 추가할 Mat 형태의 변수

- noise_num : 픽셀값을 변경할 픽셀의 개수

 

1. 노이즈를 추가할 프레임의 픽셀을 임의로 선택한다.

int col_pixel = rand() % image.cols;
int row_pixel = rand() % image.rows;

 

2. 임의 픽셀의 픽셀값을 검정색(0) 혹은 흰색(255)으로 교체한다.

int ch_num = image.channels();
int noise_color = (rand() % 2) * 255;

if(ch_num == 1)
{
	image.at<uchar>(row_pixel, col_pixel) = noise_color;
}
else if(ch_num == 3)
{
	image.at<Vec3b>(row_pixel, col_pixel)[0] = noise_color;
	image.at<Vec3b>(row_pixel, col_pixel)[1] = noise_color;
	image.at<Vec3b>(row_pixel, col_pixel)[2] = noise_color;
}

- ch_num == 1 : 흑백 영상일 경우

- ch_num == 3 : 컬러 영상일 경우

  ⇒ B, G, R 채널을 동일한 값(0 or 255)으로 교체한다.

 

 

Code

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

void addNoise(Mat &image, int noise_num);

int main(void)
{
    VideoCapture open_origin_video("vtest.avi");
    if(!open_origin_video.isOpened())
    {
        cerr << "ERROR! Unable to open the Origin Video\n";
        open_origin_video.release();
        return -1;
    }
    
    double fps = open_origin_video.get(CAP_PROP_FPS);
    int width = open_origin_video.get(CAP_PROP_FRAME_WIDTH);
    int height = open_origin_video.get(CAP_PROP_FRAME_HEIGHT);
    int fourcc = VideoWriter::fourcc('m', 'p', '4', 'v');
    
    VideoWriter save_origin_video("save_origin_video.mov", fourcc, fps, Size(width, height));
    VideoWriter save_noise_video("save_noise_video.mov", fourcc, fps, Size(width, height));
    
    while(open_origin_video.isOpened())
    {
        Mat origin_frame;
        open_origin_video >> origin_frame;
        
        if(origin_frame.empty())
        {
            cerr << "ERROR! blank Origin Frame grabbed\n";
            return 0;
        }
        
        // 원본 영상 출력, 저장
        imshow("Origin Video", origin_frame);
        save_origin_video << origin_frame;


        Mat noise_frame;
        noise_frame = origin_frame.clone();
        
        addNoise(noise_frame, 5000);    // 노이즈 추가

        // 노이즈가 적용된 영상 출력, 저장
        imshow("Noise Video", noise_frame);
        save_noise_video << noise_frame;
        
        
        if(waitKey(1000 / fps) == 'q')
        {
            break;
        }
    }
    
    open_origin_video.release();
    save_origin_video.release();
    save_noise_video.release();
    
    
    destroyAllWindows();
    
    return 0;
}


void addNoise(Mat &image, int noise_num)
{
    srand((unsigned int)time(NULL));
    
    for(int k = 0; k < noise_num; k++)
    {
        int col_pixel = rand() % image.cols;    // noise를 추가할 열을 임의로 선택
        int row_pixel = rand() % image.rows;    // noise를 추가할 행을 임의로 선택
        int ch_num = image.channels();
        int noise_color = (rand() % 2) * 255;   // 0 or 255
        
        if(ch_num == 1) // 흑백 영상
        {
            image.at<uchar>(row_pixel, col_pixel) = noise_color;    // 임의 픽셀의 픽셀값을 검정색(0) 혹은 흰색(255)으로 교체
        }
        else if(ch_num == 3)    // 컬러 영상
        {
            image.at<Vec3b>(row_pixel, col_pixel)[0] = noise_color;  // B 채널
            image.at<Vec3b>(row_pixel, col_pixel)[1] = noise_color;  // G 채널
            image.at<Vec3b>(row_pixel, col_pixel)[2] = noise_color;  // R 채널
        }
    }
}

 

 

Result

  • 원본 영상에 Salt and Pepper Noise가 추가된 새로운 영상이 화면에 출력되는 동안 새로운 영상 파일이 생성된다.

화면에 출력되는 노이즈가 추가된 영상 캡처

 

파일에 저장된 새로운 영상 캡처

 

- 영상이 종료될 경우, 생성했던 윈도우가 전부 제거된다.

 

 


GitHub

https://github.com/YunSoobin/ParallelProgramming

 

GitHub - YunSoobin/ParallelProgramming: 영상처리 알고리즘 병렬화

영상처리 알고리즘 병렬화. Contribute to YunSoobin/ParallelProgramming development by creating an account on GitHub.

github.com

 

 

728x90