2

I'm trying to access a whole channel in a 3 channel image in opencv (to replace a channel with a whole matrix, see below). Is it possible to do so without looping through the individual pixel values?

Mat RGB(320, 480, CV_8UC3)
Mat R(320, 480, CV_8UC1)
Mat G(320, 480, CV_8UC1)
Mat B(320, 480, CV_8UC1)

// First channel of RGB = R
// second channel of RGB = G
// third channel fo RGB = B
user3079474
  • 1,653
  • 2
  • 24
  • 37
  • do you want to improve performance or just make code more readable? – Micka Apr 02 '14 at 11:48
  • Improve performance... – user3079474 Apr 02 '14 at 12:01
  • 1
    since the memory layout is `BGRBGRBGR` for the first 3 pixel in the first row, you can't easily access/manipulate only one channel without extracting it first (`cv::split`) neither can you easily set some memory region to that channel without aligning it (`cv::merge`). Since there exists no "strided copy" (according to http://stackoverflow.com/questions/17090742/copying-strided-data-in-c ), I guess openCV internally uses some kind of looping but that still might be more efficient than manual looping since they might use some optimizations. – Micka Apr 02 '14 at 12:04

1 Answers1

4

Just use split and merge

Mat RGB // source mat
Mat BGR_3[3]; 
split(RGB,RGB_3);  
BGR_3[0]//do some operation Blue channel
BGR_3[1]//do some operation Green Channel
BGR_3[2]//do some operation Red channel

//later merge
Mat dst
merge(BGR_3,3,dst);  
Haris
  • 13,645
  • 12
  • 90
  • 121
  • 1
    doesnt cv::merge internally loop over all pixel? – Micka Apr 02 '14 at 11:42
  • According to doc merge creates multichannel array out of several single-channel ones, and just opposite of merge(), may be they whre doing doing it efficiently. – Haris Apr 02 '14 at 11:48
  • but is that basically more efficient than looping manually over all pixel (and merging manually)? – Micka Apr 02 '14 at 11:50
  • The could be doing it in efficient way like this http://docs.opencv.org/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html#the-efficient-way – Haris Apr 02 '14 at 11:55