2011年7月13日水曜日

画素値へのアクセス




int ch = img.channels(); // =3
//std::cout << "step:" << hsv_img.step << ", size:" << w*ch << std::endl;
int width = hsv_img.cols, height = hsv_img.rows;


hue-value gradation image





(2a) 
for(int y=0; y<height; ++y) {
     for(int x=0; x<width; ++x) {
          int a = hsv_img.step*y+(x*ch);
          hsv_img.data[a+0] = (x*180/width);
          hsv_img.data[a+1] = 255;
          hsv_img.data[a+2] = ((height-y)*255/height);
     }
}

(2b) 
for(int y=0; y<height; ++y) {
     uchar *p = hsv_img.ptr(y);
     for(int x=0; x<width; ++x) {
          p[x*ch+0] = (x*180/width);
          p[x*ch+1] = 255;
          p[x*ch+2] = ((height-y)*255/height);
     }
}


(2c) 
for(int y=0; y<height; ++y) {
     uchar *p = hsv_img.ptr(y);
     for(int x=0; x<width; ++x) {
          p[x*ch+0] = (x*180/width);
          p[x*ch+1] = 255;
          p[x*ch+2] = ((height-y)*255/height);
     }
}

(2d) 
for(int y=0; y<height; ++y) {
     for(int x=0; x<width; ++x) {
          Vec3b &p = hsv_img.at<Vec3b>(y,x);
          p[0] = (x*180/width);
          p[1] = 255;
          p[2] = ((height-y)*255/height);
     }
}


(2e) 
Mat_<Vec3b>& ref_img = (Mat_<Vec3b>&)hsv_img;
for(int y=0; y<height; ++y) {
     for(int x=0; x<width; ++x) {
          ref_img(y, x)[0] = (x*180/width);
          ref_img(y, x)[1] = 255;
          ref_img(y, x)[2] = ((height-y)*255/height);
     }
}


(2f) 
vector<Mat> planes;
split(hsv_img, planes);
MatIterator_<uchar> it_h = planes[0].begin<uchar>();
MatIterator_<uchar> it_s = planes[1].begin<uchar>();
MatIterator_<uchar> it_v = planes[2].begin<uchar>();
for(int c=0; it_h!=planes[0].end<uchar>(); ++it_h, ++it_s, ++it_v, ++c) {
     *it_h = ((c%width)*180/width);
     *it_s = 255;
     *it_v = ((height-c/width)*255/height);
}
merge(planes, hsv_img);



(2g)(when no-gap)
MatIterator_<Vec3b> it = hsv_img.begin<Vec3b>();
for(int c=0; it!=hsv_img.end<Vec3b>(); ++it,++c) {
     int x=c%width;
     int y=c/width;
     (*it)[0] = (x*180/width);
     (*it)[1] = 255;
     (*it)[2] = ((height-y)*255/height);
}



(2a)~(2e)までの速度はそれほど変わらない。



参考:
http://opencv.jp/opencv2-x-samples/access_pixel_value

0 件のコメント:

コメントを投稿