OpenCV for iOS 學(xué)習(xí)筆記(二)—— 圖像矩陣的掩碼操作

環(huán)境配置 :

OpenCV在xCode中的安裝與環(huán)境配置

矩陣掩碼操作:根據(jù)掩碼矩陣(也稱作核)重新計(jì)算圖像中每個(gè)像素的值。掩碼矩陣中的值表示近鄰像素值(包括該像素自身的值)對(duì)新像素值有多大影響。從數(shù)學(xué)觀點(diǎn)看,我們用自己設(shè)置的權(quán)值,對(duì)像素鄰域內(nèi)的值做了個(gè)加權(quán)平均。

運(yùn)行效果:

原圖
處理后

代碼示例:

void Sharpen(const Mat& myImage, Mat& Result, int n) {?

? ? ? ? CV_Assert(myImage.depth() == CV_8U); ?

? ? ? ? Result.create(myImage.size(),myImage.type());?

? ? ? ? const int nChannels = ? ? ? myImage.channels();? ? ??

? ? ? ? for(int j = 1 ; j < myImage.rows-1; ++j)? ? {? ? ? ?

? ? ? ? ? ? ? ? ?const uchar* previous = myImage.ptr(j - 1);? ?

? ? ? ? ? ? ? ? ?const uchar* current? = myImage.ptr(j );?

? ? ? ? ? ? ? ? ?const uchar* next? ? = myImage.ptr(j + 1);

? ? ? ? ? ? ? ? ?uchar* output = Result.ptr(j);?

? ? ? ? ? ? ? ? ?for(int i= nChannels; i < nChannels*(myImage.cols-1); ++i)? ? ? ? { ? ? ? ?

? ? ? ? ? ? ? ? ? ? ? ? ? *output++ = saturate_cast(n * current[i]

? ? ? ? ? ? ? ? ? ? ? ? - current[i - nChannels] - current[i+nChannels] - previous[i] - ? ?next[i]);

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? }

// 邊界處理

? ? ? ? Result.row(0).setTo(Scalar(0));? ? ? ? ? ? ? ? ? // 上

? ? ? ? Result.row(Result.rows-1).setTo(Scalar(0));? ? ? // 下

? ? ? ? Result.col(0).setTo(Scalar(0));? ? ? ? ? ? ? ? ? // 左

? ? ? ? Result.col(Result.cols-1).setTo(Scalar(0));? ? ? // 右

}

調(diào)用方式:

Mat myImage, result;

UIImage *img = [UIImage imageNamed:@"imageName"];

UIImageToMat(img, myImage); ? // 將UIImage對(duì)象轉(zhuǎn)換成 Mat

Sharpen(myImage, result, n); ? // myImage:預(yù)處理對(duì)象 result:處理結(jié)果 n:可以隨便填試試 建議在 5+-n

UIImage *img2 = MatToUIImage(result); ? ? // 將Mat轉(zhuǎn)換成 UIImage 對(duì)象


參考資料:?矩陣的掩碼操作

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容