ImageJ编程:局部颜色特征采样

336 阅读1分钟

先放代码,以后再介绍。

/* ImageJ Macro Script
 * 局部采样,获取平均的颜色特征,
 * 如色度(hue),饱和度(saturation)以及强度(intensity),
 * 采用的HSI颜色模型对RGB数值进行转换
 * 可自行定义采样区域的宽度
 * 在Log窗口输出
 */

width = 3;

main(width);

function main(width){
	waitForUser("Please click OK and then \n"+
	"choose the center of particle on the image\n"+
	"with left mouse botton!");
	loc = chooseParticle();
	getParticleHSI(loc[0],loc[1], width);
}

function getParticleHSI(x,y,width){
	// s = 3
	s = round(width/2);
	zone = pow(2*s, 2);
	hue = newArray(zone);
	sat = newArray(zone);
	val = newArray(zone);
	for (i = 0; i < 2*s; i++) {
		for (j = 0; j < 2*s; j++) {
			hsi = getHSI(x-s+i,y-s+j);
			hue[2*s*i+j] = hsi[0];
			sat[2*s*i+j] = hsi[1];
			val[2*s*i+j] = hsi[2];
		}
	}
	print("X "+ x+"\nY "+y);
	Array.getStatistics(hue, min, max, mean, stdDev);
	print("Hue "+ mean);
	Array.getStatistics(sat, min, max, mean, stdDev);
	print("Saturation "+ mean);
	Array.getStatistics(val, min, max, mean, stdDev);
	print("Intensity "+ mean);
}

function getRGB(x,y){
	RGB = newArray(3);
	v = getPixel(x,y);
	RGB[0] = (v>>16)&0xff;  // extract red byte (bits 23-17)
	RGB[1] = (v>>8)&0xff; // extract green byte (bits 15-8)
	RGB[2] = v&0xff;       // extract blue byte (bits 7-0)
	return RGB;
}

function getHSI(x,y){
	rgb = getRGB(x,y);
	HSI = RGB2HSI(rgb);
	return HSI;
}

function RGB2HSI(rgb){
	r = rgb[0]; // red
	g = rgb[1]; // green
    b = rgb[2]; // blue 0~255
    
    num = 0.5*((r-g)+(r-b));
    den = sqrt((r-g)*(r-g)+(r-b)*(g-b));
    theta = acos(num/(den+1e-6));

    h = theta;
    if (b>g) h = 2*PI - theta;
    h = h/(2*PI);

    Array.getStatistics(rgb, min, max, mean, stdDev);
    den = r+g+b;
    if (den==0) den = 1e-6;
    s = 1-3*min/den;
    if (s==0) h = 0;

    i = max;
    h = h*360;
	HSI = newArray(h,s,i);
	return HSI;
}

function chooseParticle(){
    leftButton = 16;
    flags = 0;
    while(flags&leftButton == 0) getCursorLoc(x,y,z,flags);
    return newArray(x,y);
}