http://pgsample.info/image/filter/sobel.html
C++
1#include <math.h> 2#include <cxcore.h> 3#include <cv.h> 4#include <highgui.h> 5#pragma comment(lib,"cv.lib") 6#pragma comment(lib,"cxcore.lib") 7#pragma comment(lib,"highgui.lib") 8 9void sobel(unsigned char *out, unsigned char *in, int inHeight, int inWidth, int inChannel); 10 11int main(){ 12 IplImage *in, *out; 13 14 in = cvLoadImage("./image.bmp", 0); 15 out = cvCreateImage(cvSize(in->width, in->height), in->depth, in->nChannels); 16 17 sobel((unsigned char*)out->imageData, (unsigned char*)in->imageData, in->height, in->width, in->nChannels); 18 19 cvNamedWindow("in", 1); 20 cvShowImage("in", in); 21 cvNamedWindow("out", 1); 22 cvShowImage("out", out); 23 cvWaitKey(-1); 24 25 cvDestroyWindow("in"); 26 cvDestroyWindow("out"); 27 28 cvReleaseImage( &in ); 29 cvReleaseImage( &out ); 30 31 return 0; 32} 33 34/* 35端は処理していない 36*/ 37void sobel(unsigned char *out, unsigned char *in, int inHeight, int inWidth, int inChannel){ 38 int i, j, k, l; 39 int weightH[9] = {-1, 0, 1, 40 -2, 0, 2, 41 -1, 0, 1}; 42 int weightV[9] = {-1, -2, -1, 43 0, 0, 0, 44 1, 2, 1}; 45 int *imgTmp; 46 int weightSize = 3; 47 48 int start = -1; 49 int end = start + weightSize; 50 double dataTmpH; 51 double dataTmpV; 52 double dataTmpSum; 53 int widthStep; 54 55 widthStep = inWidth * inChannel; 56 if(widthStep % 4 != 0){ 57 widthStep = widthStep + 4 - widthStep % 4; 58 } 59 60 for(i = 1; i < (inHeight - 1); ++i){ 61 for(j = 1; j < (inWidth - 1); ++j){ 62 dataTmpH = 0; 63 dataTmpV = 0; 64 for(k = start; k < end; ++k){ 65 for(l = start; l < end; ++l){ 66 // 水平方向 67 dataTmpH += weightH[(k - start) * weightSize + (l - start)] * (unsigned char)in[(i + k) * widthStep + (j + l)]; 68 69 // 垂直方向 70 dataTmpV += weightV[(k - start) * weightSize + (l - start)] * (unsigned char)in[(i + k) * widthStep + (j + l)]; 71 72 } 73 } 74 dataTmpSum = sqrt(dataTmpH * dataTmpH + dataTmpV * dataTmpV); 75 76 // 255を超えた値は255、0未満の値は絶対値 77 if(dataTmpSum > 255){ 78 dataTmpSum = 255; 79 } else if(dataTmpSum < 0){ 80 dataTmpSum = -dataTmpSum; 81 } 82 out[i * widthStep + j] = dataTmpSum; 83 } 84 } 85 86}
こちらのサイトにあるsobelフィルタのプログラムを用いて、
エッジの方向別に色分けを行うプログラムを作成しようと考えております。
まず、出力"out"を24bitカラー(8bit 3Channel)にしたいので、
C++
1 out = cvCreateImage(cvSize(in->width, in->height), IPL_DEPTH_8U, 3);
に変更し、sobel関数内のoutの部分も3チャンネルに対応させるため、
C++
1out[i * widthStep + j * 3 + 0] = dataTmpSum; 2out[i * widthStep + j * 3 + 1] = dataTmpSum; 3out[i * widthStep + j * 3 + 2] = dataTmpSum;
の様な感じにしています。まだ、色の変更プログラムは書いていません。
ここまでで、プログラムを動かしてみたのですが、出力のカラー画像が9分の1サイズかつ元画像の3分の1しか表示されません。
プログラムをどの様に改変すれば、正しいカラー画像が出力されますでしょうか。
ご教授お願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/17 06:29