OpenCv 016---圖像ROI與ROI操作


1 前備知識

null

2 所用到的主要OpenCv API

skip

3 程序代碼

#include<opencv2/opencv.hpp>
#include<iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    Mat src = imread("G:\\CVworkstudy\\program_wwx\\Research society140\\ZhaiZhigang140\\colormap.png");
    namedWindow("input", WINDOW_AUTOSIZE);
    imshow("input", src);
    int h = src.rows;
    int w = src.cols;

    //get ROI
    int cy = h / 2;
    int cx = w / 2;
    Rect rect(cx - 100, cy - 100, 200, 200);
    Mat roi = src(rect);
    imshow("roi", roi);

    Mat image = roi.clone();
    // modify ROI
    roi.setTo(Scalar(255, 0, 0));
    imshow("result", src);
    
    //modif copy roi
    image.setTo(Scalar(255, 0, 0));
    imshow("result", src);
    imshow("copy roi", image);

    //example with ROI - generate mask
    Mat src2 = imread("G:\\CVworkstudy\\program_wwx\\Research society140\\ZhaiZhigang140\\zhengjianzhao.jpg");
    imshow("src2", src2);
    Mat hsv, mask;
    cvtColor(src2, hsv, COLOR_BGR2HSV);
    //That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the
    //specified 1D, 2D, 3D, ... box and 0 otherwise.
    inRange(hsv, Scalar(100, 43, 46), Scalar(124, 255, 255), mask);//within the wise set to 255,if not,set 0
    imshow("mask", mask);//get the mask exclusive person

    //extract person ROI
    Mat person;
    bitwise_not(mask, mask);
    Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
    morphologyEx(mask, mask, MORPH_CLOSE, kernel);
    bitwise_and(src2, src2, person, mask);
    imshow("person", person);

    //generate background
    Mat result = Mat::zeros(src2.size(), src2.type());
    result.setTo(Scalar(0, 0, 255));

    //combine background + person
    Mat dst;
    bitwise_not(mask, mask);
    bitwise_or(person, result, dst, mask);
    add(dst, person, dst);

    imshow("dst", dst);
    waitKey(0);
    return 0;
}

 

4 運行結果

后面幾張圖省略,主要是實現證件照背景顏色替換,由藍色替換為紅色,顏色HSV范圍表參見:

OpenCv 009---色彩空間與色彩空間轉換

5 擴展及注意事項

null


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM