[英]How to get rgb value by cimg?
CImg<unsigned char> src("image.jpg");
int width = src.width();
int height = src.height();
unsigned char* ptr = src.data(10,10);
我如何從ptr
獲得rgb
?
在Ubuntu 10.04上測試,手工制作的3x3 RGB圖像保存為test.png
:
sudo apt-get install cimg-dev
源文件cimg_test.cpp
:
#include <iostream>
using namespace std;
#include <CImg.h>
using namespace cimg_library;
int main()
{
CImg<unsigned char> src("test.png");
int width = src.width();
int height = src.height();
cout << width << "x" << height << endl;
for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++)
cout << "(" << r << "," << c << ") ="
<< " R" << (int)src(c,r,0,0)
<< " G" << (int)src(c,r,0,1)
<< " B" << (int)src(c,r,0,2) << endl;
return 0;
}
編譯並運行:
g++ cimg_test.cpp -lX11 -lpthread -o cimg_test ./cimg_test 3x3 (0,0) = R0 G0 B0 (0,1) = R255 G0 B0 (0,2) = R0 G255 B0 (1,0) = R0 G0 B255 (1,1) = R128 G128 B128 (1,2) = R0 G0 B128 (2,0) = R128 G0 B0 (2,1) = R0 G128 B0 (2,2) = R255 G255 B255
有用。
從CImg文檔 - 第34頁的第6.13節和第120頁的第8.1.4.16節 - 看起來data
方法可以采用四個參數 :x,y,z和c:
T* data(const unsigned int x, const unsigned int y = 0,
const unsigned int z = 0, const unsigned int c = 0)
...其中c
指的是顏色通道。 我猜測如果你的圖像確實是一個RGB圖像,那么對c
使用0,1或2的值將給出給定x, y
位置的紅色,綠色和藍色分量。
例如:
unsigned char *r = src.data(10, 10, 0, 0);
unsigned char *g = src.data(10, 10, 0, 1);
unsigned char *b = src.data(10, 10, 0, 2);
(但這只是猜測!)
編輯:
它看起來像CImg的operator()以類似的方式工作:
unsigned char r = src(10, 10, 0, 0);
訪問數據的最簡單方法是使用()
運算符:
unsigned char r = img(10,10,0,0);
unsigned char g = img(10,10,0,1);
unsigned char b = img(10,10,0,2);
你可能會感到困惑,因為CImg存儲了非交錯的原始數據。 即您的原始數據存儲R1, R2, ..., G1, G2, ..., B1, B2, ...
而不是R1, G1, B1, R2, G2, B2, ...
請參閱: http: //cimg.eu/reference/group__cimg__storage.html
.data()
只返回一個指針,所以要像上面那樣直接訪問數據:
CImg<unsigned char> src("image.jpg");
int width = src.width();
int height = src.height();
unsigned char* ptr = src.data(10,10);
unsigned char r = ptr[0];
unsigned char g = ptr[0+width*height];
unsigned char b = ptr[0+2*width*height];
@wamp:我不知道CImg,但RGB中的灰度圖像有:
R = G = B.
在CMYK:
C = M = Y = 0
K =亮度
所以你甚至不需要一個功能......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.