Question: I am trying to take a colored image and make two different verisons of this image. I have figured out how to output a proper
I am trying to take a colored image and make two different verisons of this image. I have figured out how to output a proper grayscale image but I cannot understand the logic of outputting the second verison which is a threshold image. I have identified my threshold value but cannot figure out how to properly output the image. In my code the threshold value is "maxInd". I have tried using an if else statement to make the output work but it is making an all white copy of the new grayscale and the new image. The code needs to look at the pixels and determine if the current pixel value is greater than or equal to the threshold amount, it would assign that pixel to 255, if it is less, it would assign it to zero. I have attached my code below:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class GrayScale
{
BufferedImage image, thresHold;
int width;
int height;
int grayScale;
int maxInd = 0;
public GrayScale(){
try{
File input = new File("mysteryBird.jpg");
image = ImageIO.read(input);
width = image.getWidth();
height= image.getHeight();
int hist[] = new int[256];
for (int i = 0; i for(int j = 0; j < width; j++){ Color c = new Color(image.getRGB(j,i)); int red = (int)(c.getRed() * 0.299); int green =(int)(c.getGreen() * 0.587); int blue = (int)(c.getBlue() * 0.114); Color newColor = new Color(red+green+blue,red+green+blue,red+green+blue); grayScale=red+blue+green; hist[grayScale] += 1; // increment hist[grayScale] by 1 image.setRGB(j,i,newColor.getRGB()); if(grayScale >= maxInd){ Color thresh = new Color(255,255,255); thresHold.setRGB(j,i,thresh.getRGB()); } else { Color thresh = new Color(0,0,0); thresHold.setRGB(j,i,thresh.getRGB()); } } } for(int k = 0;k System.out.println("pixel value: " +k+ " found " + hist[k]+" times"); } // calculating threshold value for (int i = 0; i < hist.length; ++i) { if(hist[i] > hist[maxInd]) { maxInd = i; } } System.out.println(maxInd + " appeared most (" + hist[maxInd] + ") number of times"); System.out.println("So, Threshold value is " + maxInd); File output = new File("grayscale.jpg"); ImageIO.write(image, "jpg", output); File output2 = new File("threshold.jpg"); ImageIO.write(image, "jpg", output2); } catch (Exception e){} } public static void main(String args[]) throws Exception{ GrayScale obj = new GrayScale(); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
