Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to convert image color to Gray Scale using OpenCV?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 427
    Comment on it

    OpenCV library is useful to convert image background color to another RGB color.

    We basically read the image using BufferedImage then we read bytes data from that image and we create a new MAT by applying image height and width and then put that byte data in MAT.

     

    cvtColor is basically used to convert the one color space to another color space. ImageIO is basically used to read and write the image file.

    public class MainActivity extends AppCompatActivity {
          try {
             System.loadLibrary("opencv_java3");
             File input = new File("imageProcessing.jpg");
             BufferedImage bufferedImage = ImageIO.read(input);	
    
             byte[] byteData = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
             Mat mat = new Mat(bufferedImage.getHeight(), bufferedImage.getWidth(), CvType.CV_8UC3);
             mat.put(0, 0, byteData);
    
             Mat mat1 = new Mat(bufferedImage.getHeight(),bufferedImage.getWidth(),CvType.CV_8UC1);
             Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);
    
             byte[] byteData1 = new byte[mat1.rows() * mat1.cols() * (int)(mat1.elemSize())];
             mat1.get(0, 0, data1);
             BufferedImage bufferedImage1 = new BufferedImage(mat1.cols(),mat1.rows(), BufferedImage.TYPE_BYTE_GRAY);
             bufferedImage1.getRaster().setDataElements(0, 0, mat1.cols(), mat1.rows(), data1);
    
             File ouptut = new File("resultingGrayImg.jpg");
             ImageIO.write(bufferedImage1, "jpg", ouptut);
             
          } catch (Exception e) {
             System.out.println("Error: " + e.getMessage());
          }
       }
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: