Detailed Java how to realize the _java of image grayscale

Source: Internet
Author: User
Tags scale image

24-bit color graphs and 8-bit gray scale graphs

First of all, introduce 24-bit color image, in a 24-bit color image, each pixel is represented by three bytes, usually represented as RGB. Typically, many 24-bit color images are stored as 32-bit images, and each pixel's excess bytes are stored as a alpha value, with a special effect on the message [1].

In the RGB model, if r=g=b, then color represents a grayscale color, where the value of r=g=b is called Gray value, therefore, gray-scale image per pixel only one byte of gray value (also known as strength value, brightness value), gray range of 0-255[2]. This will get a grayscale image of the picture.

Several methods of gray-scale

1. Component method: using one of the RGB three components as the grayscale value of the grayscale image.

2, the most value method: using RGB three components of the maximum or minimum value as the gray-scale value of the grayscale map.

3. Mean method: using the average value of RGB three components as grayscale values of gray scale graphs.

4, weighted method: because the color sensitivity of the human eye is different, according to a certain weight of the RGB three components weighted average can get more reasonable gray image. In general, follow: Y = 0.30R + 0.59G + 0.11B.

The weighting method actually takes the brightness value of a picture as the gray value to calculate, and uses the YUV model. In [3] it is found that the author used the y = 0.21 * r + 0.71 * g + 0.07 * b to compute the gray value (obviously the three weights are not equal to 1, possibly the author's error?). )。 In practice, this difference should be related to whether or not gamma correction is used [1].

A method of Java to realize gray scale

If you search for "Java to achieve grayscale," it is a Method (code):

public void Grayimage () throws ioexception{
 File File = new file (System.getproperty ("User.dir") + "/test.jpg");
 BufferedImage image = (file);
 int width = image.getwidth (); 
 int height = image.getheight (); 
 BufferedImage grayimage = new BufferedImage (width, height, bufferedimage.type_byte_gray); 
 for (int i= 0; i < width; i++) {for 
  (int j = 0; j < height; J +) { 
  int rgb = Image.getrgb (i, j); 
  Grayimage.setrgb (i, J, RGB); 
 File NewFile = new file (System.getproperty ("User.dir") + "/method1.jpg"); 
 Imageio.write (grayimage, "JPG", newFile); 

Test.jpg's original artwork is:

Using the above method to get the grayscale map:

It seems to be quite feasible to see this grayscale image, but if we use it opencv to achieve grayscale or use PIL (Python), you will find that the effect is very different:

img = cv2.imread (' test.jpg ', Cv2. Imread_color)
Gray = Cv2.cvtcolor (img,cv2. Color_bgr2gray)
cv2.imwrite (' pythonmethod.jpg ', gray)

It is clear to see that the opencv gray-scale image obtained by using (PiL is the same) is much better than the Java method above, and can be seen in many details. This shows that this popular approach to the Internet has always been a problem, but has been ignored.

How to achieve the OpenCV of gray scale

If you read the opencv relevant books or code, you probably know that the opencv gray-scale use of the weighted method, the reason is probably, because we do not know why the opencv grayscale image so good, whether there are other processing details we ignore?

Verify that our conjecture is simple, as long as you look at the pixel values before and after the changes are known, you can test the following:

img = cv2.imread (' test.jpg ', Cv2. Imread_color)
h, w = img.shape[:2]
Gray = Cv2.cvtcolor (img,cv2. Color_bgr2gray) for
J in Range (W): For
 I in Range (h):
  print str (i) + ":" + str (j) + "" + str (GRAY[I][J])
Print Img[h-1][w-1][0:3]

The following print so many pixel points, we are very difficult to judge, but we just focus on the last pixel, we can find clues: The original image of the last pixel RGB value is 44,67,89, and the gray value after 71. The gray value that fits exactly the weighted method. If you check the pixel values of a picture that was previously gray in Java, you'll find that not only does the pixel value not conform to the formula, it's even far apart.

In this way, we speculate that OpenCV (also including PIL) is grayscale using the weighted method.

Java implementation weighted method of gray

If the popular method on the Internet does not work, how can we use Java to achieve grayscale? In fact [3] has been successfully implemented (a variety of methods) grayscale (foreign friends to do the technology or very strong), here only to extract the necessary code:

private static int Colortorgb (int alpha, int red, int green, int blue) {int newpixel = 0;
  Newpixel = Alpha;
  Newpixel = Newpixel << 8;
  Newpixel + = red;
  Newpixel = Newpixel << 8;
  Newpixel + = green;
  Newpixel = Newpixel << 8;
  Newpixel = blue;
return newpixel; public static void Main (string[] args) throws IOException {BufferedImage bufferedimage = (New File (Syst
 Em.getproperty ("User.dir" + "/test.jpg")); BufferedImage grayimage = new BufferedImage (Bufferedimage.getwidth (), bufferedimage.getheight (), buffer
 Edimage.gettype ()); for (int i = 0; i < bufferedimage.getwidth (); i++) {for (int j = 0; J < Bufferedimage.getheight (); j + +) {FINA
   l INT color = Bufferedimage.getrgb (i, j);
   Final int r = (color >>) & 0xFF;
   Final int g = (color >> 8) & 0xFF;
   final int b = color & 0xff;
   int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);; SYSTEM.OUT.PRINTLN (i + ":")+ j + "" + gray);
   int newpixel = COLORTORGB (255, gray, Gray, gray);
  Grayimage.setrgb (i, J, Newpixel);
 } File newFile = new File (System.getproperty ("User.dir") + "/ok.jpg");
Imageio.write (grayimage, "JPG", newFile); }

The above code prints out the grayscale pixel value, and if you compare it to the Python code above, you'll see that the pixel value is completely matched. colorToRGBin this method, the processing of a color graph is exactly 4 bytes, one of which is the alpha parameter (as described above), and the following image is the gray of the Code:

For other methods, the same can be done in turn.


The reason for this article is that we want to use Java to achieve several kinds of gray operation, and using OPENCV to verify the transformation of the right and wrong, but in the actual test found some problems (after the transformation of the picture has a difference, and how to transform the gray scale after the conversion of gray-scale map and other issues), and in this way a certain number of thinking and verification. Here need to note that some articles on the Web more or less do not do further thinking (even many are copied, especially in the domestic article), and for these practical problems, hands-on implementation and validation is a very important method. I hope the contents of this article can be helpful to everyone. If you have questions, you can leave a message for discussion.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.