专栏地址:http://blog.csdn.net/column/details/imagep.html
本篇文章主要记录一下图像处理软件中的图像特效(素描和油画)的实现过程。
图像素描效果
图像素描的实现原理其实很简单,主要是利用边缘检测滤波器来实现。
可供选择的边缘检测滤波器有很多,常用的有Sobel、Scharr、Laplacian以及Canny滤波。本文主要是利用Laplacian来实现素描化,它的效果相对于Sobel和Scharr更加相像素描效果。
Laplacian算子是一个二阶导数算子,具有各向同性,即与坐标轴方向无关,坐标轴旋转后梯度结果不变。但是,它对噪声比较敏感,所以我们这里先利用中值滤波器对图像进行去噪处理。
Laplacian常用的卷积核来近似,如下图所示:
Code:
void MainWindow::on_actionSketch_triggered()
{
cv::Mat gray;
cv::cvtColor(image,gray,CV_BGR2GRAY);
const int MEDIAN_BLUR_FILTER_SIZE = 7;
cv::medianBlur(gray,gray,MEDIAN_BLUR_FILTER_SIZE);
cv::Mat edges;
const int LAPLACIAN_FILTER_SIZE = 5;
cv::Laplacian(gray,edges,CV_8U,LAPLACIAN_FILTER_SIZE);
cv::Mat mask;
const int EDGE_THRESHOLD = 50;
cv::threshold(edges,mask,EDGE_THRESHOLD,255,cv::THRESH_BINARY_INV);
QImage simg = QImage((const unsigned char*)(mask.data),mask.cols,mask.rows,
QImage::Format_Indexed8);
//ui->Imagedisplaylabel->setPixmap(QPixmap::fromImage(simg));
//ui->Imagedisplaylabel->setScaledContents(true);
//ui->Imagedisplaylabel->resize(ui->Imagedisplaylabel->width(),ui->Imagedisplaylabel->height());
}
图像油画效果
关于图像的油画效果,本文是先利用双边滤波器(见我的博客),将图像的区域推平,然后再将上面的素描效果叠加到经滤波后的图像上,如此即可实现图像的油画效果。
Code:
void MainWindow::on_actionCartoon_triggered()
{
cv::Mat gray;
cv::cvtColor(image,gray,CV_BGR2GRAY);
const int MEDIAN_BLUR_FILTER_SIZE = 7;
cv::medianBlur(gray,gray,MEDIAN_BLUR_FILTER_SIZE);
cv::Mat edges;
const int LAPLACIAN_FILTER_SIZE = 5;
cv::Laplacian(gray,edges,CV_8U,LAPLACIAN_FILTER_SIZE);
cv::Mat mask ;
const int EDGE_THRESHOLD = 90;
cv::threshold(edges,mask,EDGE_THRESHOLD,255,cv::THRESH_BINARY_INV);
cv::Size size = image.size();
cv::Size smallSize;
smallSize.width = size.width/2;
smallSize.height = size.height/2;
cv::Mat smallImg = cv::Mat(smallSize,CV_8UC3);
cv::resize(image,smallImg,smallSize,0,0,cv::INTER_LINEAR);
cv::Mat tmp = cv::Mat(smallSize,CV_8UC3);
int repetitions = 9;
for (int i = 0; i < repetitions; i++)
{
int ksize = 9;
double sigmaColor = 9;
double sigmaSpace = 7;
cv::bilateralFilter(smallImg,tmp,ksize,sigmaColor,sigmaSpace);
cv::bilateralFilter(tmp,smallImg,ksize,sigmaColor,sigmaSpace);
}
cv::Mat bigImg;
cv::resize(smallImg,bigImg,image.size(),0,0,cv::INTER_LINEAR);
cv::Mat cartoon= cv::Mat(image.size(),CV_8UC3);
memset((char*)cartoon.data,0,cartoon.step * cartoon.rows);
bigImg.copyTo(cartoon,mask);
cv::imwrite("./mask1.jpg",cartoon);
ui->textBrowser->clear();
ui->textBrowser->append("<img src= ./mask1.jpg>");
}
效果:(华大主楼)
更多关于图像处理、机器视觉资料,请关注博客:LinJM-机器视觉 微博:林建民-机器视觉