Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

// Функция пилообразного контрастирования с порогами и заданным направлением private…

  1. User

    // Функция пилообразного контрастирования с порогами и заданным направлением private BufferedImage sawtoothContrast(BufferedImage image, float t1, float t2, boolean up, boolean down) { BufferedImage output = new BufferedImage(image.getWidth(), image.getHeight(), image.getType()); for (int i = 0; i < image.getWidth(); i++) { for (int j = 0; j < image.getHeight(); j++) { int pixel = image.getRGB(i, j); int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = pixel & 0xff; int brightness = (int) (0.2126 * red + 0

  2. Assistant

    .7152 * green + 0.0722 * blue); // вычисление яркости пикселя if (up && brightness >= t2) { // если выбрано направление повышения контраста и яркость выше второго порога int newBrightness = (int) (255 * ((float) (brightness - t2) / (255 - t2))); // вычисляем новое значение яркости пикселя red = Math.min(255, Math.max(0, (int) (red * ((float) newBrightness / brightness)))); // корректируем цветовые компоненты green = Math.min(255, Math.max(0, (int) (green * ((float) newBrightness / brightness))))); blue = Math.min(255, Math.max(0, (int) (blue * ((float) newBrightness / brightness))))); } else if (down && brightness <= t1) { // если выбрано направление понижения контраста и яркость ниже первого порога int newBrightness = (int) (255 * ((float) brightness / t1)); // вычисляем новое значение яркости пикселя red = Math.min(255, Math.max(0, (int) (red * ((float) newBrightness / brightness)))); // корректируем цветовые компоненты green = Math.min(255, Math.max(0, (int) (green * ((float) newBrightness / brightness))))); blue = Math.min(255, Math.max(0, (int) (blue * ((float) newBrightness / brightness))))); } output.setRGB(i, j, (red << 16) | (green << 8) | blue); // устанавливаем новый цвет пикселя в выходном изображении } } return output; // возвращаем выходное изображение }

    // Пример использования BufferedImage inputImage = ImageIO.read(new File("input.jpg")); BufferedImage outputImage = sawtoothContrast(inputImage, 100, 200, true, false); ImageIO.write(outputImage, "jpeg", new File("output.jpg"));

    // В данном примере применяется пилообразное контрастирование к изображению input.jpg. // Выбираются пороги t1 = 100 и t2 = 200, и направление контрастирования - повышение (up = true) и понижение (down = false). // Результат сохраняется в файл output.jpg.

  3. User

    this method getHistogram(BufferedImage) and createHistogramPanel( int[], String) is undefined for the type ImageReader. Fix this. // Гистограмма для sawtooth1Image() private void sawtooth1Image() { if (image != null) { float t1 = 0, t2 = 0; boolean valid = false; while (!valid) { t1 = userInput("Введите значение порога 1: ", 0, 1); t2 = userInput("Введите значение порога 2: ", 0, 1); if (t2 > t1) { valid = true; } else { JOptionPane.showMessageDialog(null, "Значение порога 2 должно быть больше порога 1"); } }

    		BufferedImage sawtoothContrastImage = sawtoothContrast(image, t1, t2, true, false);
    
    		setImageIcon(sawtoothContrastImage);
    		saveImage(sawtoothContrastImage);
    
    		int[] originalHistogram = getHistogram(image);
    		int[] sawtoothHistogram = getHistogram(sawtoothContrastImage);
    
    		JFrame histogramFrame = new JFrame("Гистограммы");
    		histogramFrame.setLayout(new GridLayout(1, 2, 10, 10));
    
    		JPanel originalHistogramPanel = createHistogramPanel(originalHistogram, "Гистограмма исходного изображения");
    
    		JPanel sawtoothHistogramPanel = createHistogramPanel(sawtoothHistogram, "Гистограмма после контрастирования");
    
    		histogramFrame.add(originalHistogramPanel);
    		histogramFrame.add(sawtoothHistogramPanel);
    		histogramFrame.pack();
    		histogramFrame.setLocationRelativeTo(null);
    		histogramFrame.setVisible(true);
    		}
    		}
    
    		// Гистограмма для sawtooth2Image()
    		private void sawtooth2Image() {
    		if (image != null) {
    		float t1 = 0, t2 = 0;
    		boolean valid = false;
    		while (!valid) {
    		t1 = userInput("Введите значение порога 1: ", 0, 1);
    		t2 = userInput("Введите значение порога 2: ", 0, 1);
    		if (t2 > t1) {
    		valid = true;
    		} else {
    		JOptionPane.showMessageDialog(null, "Значение порога 2 должно быть больше порога 1");
    		}
    		}
    
    		BufferedImage sawtoothContrastImage = sawtoothContrast(image, t1, t2, false, true);
    
    		setImageIcon(sawtoothContrastImage);
    		saveImage(sawtoothContrastImage);
    
    		int[] originalHistogram = getHistogram(image);
    		int[] sawtoothHistogram = getHistogram(sawtoothContrastImage);
    
    		JFrame histogramFrame = new JFrame("Гистограммы");
    		histogramFrame.setLayout(new GridLayout(1, 2, 10, 10));
    
    		JPanel originalHistogramPanel = createHistogramPanel(originalHistogram, "Гистограмма исходного изображения");
    
    		JPanel sawtoothHistogramPanel = createHistogramPanel(sawtoothHistogram, "Гистограмма после контрастирования");
    
    		histogramFrame.add(originalHistogramPanel);
    		histogramFrame.add(sawtoothHistogramPanel);
    		histogramFrame.pack();
    		histogramFrame.setLocationRelativeTo(null);
    		histogramFrame.setVisible(true);
    		}
    		}
    
    		// Гистограмма для sawtooth3Image()
    		private void sawtooth3Image() {
    		if (image != null) {
    		float t1 = 0, t2 = 0;
    		boolean valid = false;
    		while (!valid) {
    		t1 = userInput("Введите значение порога 1: ", 0, 1);
    		t2 = userInput("Введите значение порога 2: ", 0, 1);
    		if (t2 > t1) {
    		valid = true;
    		} else {
    		JOptionPane.showMessageDialog(null, "Значение порога 2 должно быть больше порога 1");
    		}
    		}
    
    		BufferedImage sawtoothContrastImage = sawtoothContrast(image, t1, t2, true, true);
    
    		setImageIcon(sawtoothContrastImage);
    		saveImage(sawtoothContrastImage);
    
    		int[] originalHistogram = getHistogram(image);
    		int[] sawtoothHistogram = getHistogram(sawtoothContrastImage);
    
    		JFrame histogramFrame = new JFrame("Гистограммы");
    		histogramFrame.setLayout(new GridLayout(1, 2, 10, 10));
    
    		JPanel originalHistogramPanel = createHistogramPanel(originalHistogram, "Гистограмма исходного изображения");
    
    		JPanel sawtoothHistogramPanel = createHistogramPanel(sawtoothHistogram, "Гистограмма после контрастирования");
    
    		histogramFrame.add(originalHistogramPanel);
    		histogramFrame.add(sawtoothHistogramPanel);
    		histogramFrame.pack();
    		histogramFrame.setLocationRelativeTo(null);
    		histogramFrame.setVisible(true);
    		}
    		}
    
    		// Гистограмма для sawtooth4Image()
    		private void sawtooth4Image() {
    		if (image != null) {
    		float t1 = 0, t2 = 0;
    		boolean valid = false;
    		while (!valid) {
    		t1 = userInput("Введите значение порога 1: ", 0, 1);
    		t2 = userInput("Введите значение порога 2: ", 0, 1);
    		if (t2 > t1) {
    		valid = true;
    		} else {
    		JOptionPane.showMessageDialog(null, "Значение порога 2 должно быть больше порога 1");
    		}
    		}
    
    		BufferedImage sawtoothContrastImage = sawtoothContrast(image, t1, t2, false, false);
    
    		setImageIcon(sawtoothContrastImage);
    		saveImage(sawtoothContrastImage);
    
    		int[] originalHistogram = getHistogram(image);
    		int[] sawtoothHistogram = getHistogram(sawtoothContrastImage);
    
    		JFrame histogramFrame = new JFrame("Гистограммы");
    		histogramFrame.setLayout(new GridLayout(1, 2, 10, 10));
    
    		JPanel originalHistogramPanel = createHistogramPanel(originalHistogram, "Гистограмма исходного изображения");
    
    		JPanel sawtoothHistogramPanel = createHistogramPanel(sawtoothHistogram, "Гистограмма после контрастирования");
    
    		histogramFrame.add(originalHistogramPanel);
    		histogramFrame.add(sawtoothHistogramPanel);
    		histogramFrame.pack();
    		histogramFrame.setLocationRelativeTo(null);
    		histogramFrame.setVisible(true);
    		}
    		}
    
  4. Assistant

    The errors suggest that the methods getHistogram(BufferedImage) and createHistogramPanel(int[], String) are not defined in the class ImageReader. You need to define these two methods in the ImageReader class or move them to another helper class and import it into the ImageReader class. Here are some possible implementations of these methods:

    // Calculate histogram for a BufferedImage
    private int[] getHistogram(BufferedImage image) {
        int[] histogram = new int[256];
    
        for (int i = 0; i < image.getWidth(); i++) {
            for (int j = 0; j < image.getHeight(); j++) {
                int pixel = image.getRGB(i, j);
                int red = (pixel >> 16) & 0xff;
                int green = (pixel >> 8) & 0xff;
                int blue = pixel & 0xff;
                int brightness = (int) (0.2126 * red + 0.7152 * green + 0.0722 * blue); // calculate pixel brightness
                histogram[brightness]++;
            }
        }
    
        return histogram;
    }
    
    // Create a JPanel with a histogram plot
    private JPanel createHistogramPanel(int[] histogram, String title) {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(title));
    
        int maxValue = 0;
        for (int i = 0; i < histogram.length; i++) {
            maxValue = Math.max(maxValue, histogram[i]);
        }
    
        // Draw histogram plot using a JComponent
        JComponent histogramComponent = new JComponent() {
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.BLACK);
                g2d.drawLine(0, getHeight() - 1, getWidth() - 1, getHeight() - 1);
                g2d.drawLine(0, 0, 0, getHeight() - 1);
                for (int i = 0; i < histogram.length; i++) {
                    int x = i * getWidth() / histogram.length;
                    int y = getHeight() - 1 - histogram[i] * (getHeight() - 1) / maxValue;
                    g2d.drawLine(x, getHeight() - 1, x, y);
                }
            }
        };
    
        panel.add(histogramComponent);
    
        return panel;
    }
    

    You can add these methods to the ImageReader class and try running the program again.

  5. User

    Local variable maxValue defined in an enclosing scope must be final. Fix this. // Create a JPanel with a histogram plot private JPanel createHistogramPanel(int[] histogram, String title) { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(title));

    		int maxValue = 0;
    		for (int i = 0; i < histogram.length; i++) {
    		maxValue = Math.max(maxValue, histogram[i]);
    		}
    
    		// Draw histogram plot using a JComponent
    		JComponent histogramComponent = new JComponent() {
    		protected void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		Graphics2D g2d = (Graphics2D) g;
    		g2d.setColor(Color.BLACK);
    		g2d.drawLine(0, getHeight() - 1, getWidth() - 1, getHeight() - 1);
    		g2d.drawLine(0, 0, 0, getHeight() - 1);
    		for (int i = 0; i < histogram.length; i++) {
    		int x = i * getWidth() / histogram.length;
    		int y = getHeight() - 1 - histogram[i] * (getHeight() - 1) / maxValue;
    		g2d.drawLine(x, getHeight() - 1, x, y);
    		}
    		}
    		};
    
    		panel.add(histogramComponent);
    
    		return panel;
    		}
    
  6. Assistant

    The error message suggests that the local variable maxValue used inside the paintComponent() method must be final.

    To fix this, you can declare maxValue as final outside the anonymous class and initialize it inside the for loop:

    private JPanel createHistogramPanel(int[] histogram, String title) {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(title));
    
        final int maxValue; // declare as final
        for (maxValue = 0; maxValue < histogram.length; maxValue++) {
            maxValue = Math.max(maxValue, histogram[i]);
        }
    
        // Draw histogram plot using a JComponent
        JComponent histogramComponent = new JComponent() {
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.BLACK);
                g2d.drawLine(0, getHeight() - 1, getWidth() - 1, getHeight() - 1);
                g2d.drawLine(0, 0, 0, getHeight() - 1);
                for (int i = 0; i < histogram.length; i++) {
                    int x = i * getWidth() / histogram.length;
                    int y = getHeight() - 1 - histogram[i] * (getHeight() - 1) / maxValue;
                    g2d.drawLine(x, getHeight() - 1, x, y);
                }
            }
        };
    
        panel.add(histogramComponent);
    
        return panel;
    }
    

    This should fix the error.

  7. User

    i cannot be resolved to a variable. Fix this. // Create a JPanel with a histogram plot private JPanel createHistogramPanel(int[] histogram, String title) { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder(title));

    			final int maxValue; // declare as final
    			for (maxValue = 0; maxValue < histogram.length; maxValue++) {
    			maxValue = Math.max(maxValue, histogram[i]);
    			}
    
    			// Draw histogram plot using a JComponent
    			JComponent histogramComponent = new JComponent() {
    			protected void paintComponent(Graphics g) {
    			super.paintComponent(g);
    			Graphics2D g2d = (Graphics2D) g;
    			g2d.setColor(Color.BLACK);
    			g2d.drawLine(0, getHeight() - 1, getWidth() - 1, getHeight() - 1);
    			g2d.drawLine(0, 0, 0, getHeight() - 1);
    			for (int i = 0; i < histogram.length; i++) {
    			int x = i * getWidth() / histogram.length;
    			int y = getHeight() - 1 - histogram[i] * (getHeight() - 1) / maxValue;
    			g2d.drawLine(x, getHeight() - 1, x, y);
    			}
    			}
    			};
    
    			panel.add(histogramComponent);
    
    			return panel;
    			}
    
  8. Assistant

    The error message "i cannot be resolved to a variable" suggests that the variable i used inside the for loop in the createHistogramPanel() method is not defined.

    To fix this, you can replace maxValue[i] with maxValue:

    private JPanel createHistogramPanel(int[] histogram, String title) {
        JPanel panel = new JPanel();
        panel.setBorder(BorderFactory.createTitledBorder(title));
    
        final int maxValue;
        for (maxValue = 0; maxValue < histogram.length; maxValue++) {
            maxValue = Math.max(maxValue, histogram[maxValue]);
        }
    
        // Draw histogram plot using a JComponent
        JComponent histogramComponent = new JComponent() {
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(Color.BLACK);
                g2d.drawLine(0, getHeight() - 1, getWidth() - 1, getHeight() - 1);
                g2d.drawLine(0, 0, 0, getHeight() - 1);
                for (int i = 0; i < histogram.length; i++) {
                    int x = i * getWidth() / histogram.length;
                    int y = getHeight() - 1 - histogram[i] * (getHeight() - 1) / maxValue;
                    g2d.drawLine(x, getHeight() - 1, x, y);
                }
            }
        };
    
        panel.add(histogramComponent);
    
        return panel;
    }
    

    This should fix the error.