如何在java中为任何像素设置特定值?
实际上,我正在从事一些图像处理项目,并在某个地方受到了打击。我必须将彩色图像转换为灰度,为此我使用以下命令提取了像素的 RED、GREEN、BLUE 分量的值GETRGB()
n 现在我想将该像素的 RGB 值设置为其 RGB 分量的平均值。 RGB 分量分别存储在 INT 变量中,那么你可以帮我将这个 RGB 分量的平均值设置为原始像素值吗? 代码的部分是:
rgbArray=new int[w*h];
buffer.getRGB(0, 0, width, height, rgbArray , 0,width );
int a,r,g,b;
for(int i = 0 ; i<w*h; i++)
{
r = (0x00ff0000 & rgbArray[i]) >> 16;
g = (0x0000ff00 & rgbArray[i]) >> 8;
b = (0x000000ff & rgbArray[i]);
rgbArray[i] = (r+g+b)/3;
}
buffer.setRGB(0, 0, width, height, rgbArray , 0,width);
但这并没有给我一个灰色的图像。你能告诉我我哪里做错了吗?
Actually I'm working on some image processing project and got struck somewhere. I have to convert the colored image to grey scale and for this i have extracted the values of RED, GREEN, BLUE component of a pixel using GETRGB()
n now I want to set the RGB value of that pixel equal to the average of its RGB component. The RGB components are stored in INT variables respectively, so can u help me to set the average of this RGB components to the original pixel value??
The part of the code is :
rgbArray=new int[w*h];
buffer.getRGB(0, 0, width, height, rgbArray , 0,width );
int a,r,g,b;
for(int i = 0 ; i<w*h; i++)
{
r = (0x00ff0000 & rgbArray[i]) >> 16;
g = (0x0000ff00 & rgbArray[i]) >> 8;
b = (0x000000ff & rgbArray[i]);
rgbArray[i] = (r+g+b)/3;
}
buffer.setRGB(0, 0, width, height, rgbArray , 0,width);
but this is not giving me a grey image. Can u tell where i am doing a mistake.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前尚不清楚你想做什么。如果您尝试产生灰色,我建议参考以下页面: http://www.tayloredmktg.com /rgb/ 显示不同灰度的 rgb 代码。
如果您想获得半透明图像,则必须使用 java 中的 alpha 通道(RGBA 命令)。您还可以通过以特殊方式将底层图像与当前图像合成来获得半透明效果,但这比使用 Alpha 通道要困难得多。
It is not clear what you want to do. If you are trying to produce a gray color I suggest referring to the following page: http://www.tayloredmktg.com/rgb/ which shows rgb codes for different shades of gray.
If you are trying to get a translucent image you have to use the alpha channel (RGBA commands) in java. You can also get translucency by compositing the underlying image with your current image in special ways but that is MUCH harder than using alpha channel.
您的代码不会将灰度级打包回每个颜色分量中。另外,正如我在对该问题的评论中所说,转换为灰度需要考虑人眼对每种颜色成分的敏感度。获取灰度级的典型公式
如这篇维基百科文章所述。
因此,您的
for
循环应如下所示:当然,您可以在循环外部声明
gray
,就像您对r
所做的那样。Your code does not pack the grayscale level back into each color component. Also, as I said in my comment to the question, conversion to grayscale needs to consider the human eye's sensitivity to each color component. A typical formula for obtaining the gray level is
as this Wikipedia article states.
So your
for
loop should look like this:You can, of course, declare
gray
outside of the loop, like you did withr
, etc.