Skip to Content
CoursesCSC102การกลับสีภาพโทนสีเทา

การกลับสีภาพโทนสีเทา

โจทย์

Write a program to invert the colors of a grayscale image represented by a 2D array, where each pixel value ranges from 0 to 255, write a program to invert the colors of the image.

Input:

  • The first line contains two integers n and m, representing the number of rows and columns of the grayscale image.
  • The next n lines each contain m integers, representing the pixel values of the image, where each value is in the range [0, 255].

Output:

  • There are n lines of output, where each line contains m integers representing the inverted pixel values.

Hint:

  • Inversion Formula: inverted_value = 255 - original_value
  • Math.abs()
InputOutput
3 3
0 128 255
64 32 16
255 200 100
255 127 0
191 223 239
0 55 155

โค้ด

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int [][] grayscaleImage = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { grayscaleImage[i][j] = scanner.nextInt(); } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.printf("%d ", Math.abs(255 - grayscaleImage[i][j])); } System.out.println(); } } }

คำอธิบาย

1. การประกาศคลาสและ Import

import java.util.Scanner; public class Program { public static void main(String[] args) {
  • import java.util.Scanner: นำเข้าคลาส Scanner สำหรับรับข้อมูล
  • public class Program: ประกาศคลาสหลัก
  • public static void main: เมธอดหลักที่จะทำงานเมื่อรันโปรแกรม

2. การรับข้อมูล

Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt();
  • สร้างออบเจ็กต์ Scanner สำหรับรับข้อมูล
  • รับค่าจำนวนแถว (n) และคอลัมน์ (m)

3. การสร้างและเก็บข้อมูลภาพ

int[][] grayscaleImage = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { grayscaleImage[i][j] = scanner.nextInt(); } }
  • สร้างอาเรย์ 2 มิติขนาด n×m
  • ใช้ loop ซ้อนเพื่อรับค่าพิกเซลทีละตำแหน่ง

4. การกลับสีและแสดงผล

for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { System.out.printf("%d ", Math.abs(255 - grayscaleImage[i][j])); } System.out.println(); }
  • ใช้ loop ซ้อนวนทุกพิกเซล
  • คำนวณค่าสีที่กลับด้วยสูตร: 255 - original_value
  • ใช้ Math.abs() เพื่อให้แน่ใจว่าได้ค่าบวกเสมอ
  • พิมพ์ค่าที่คำนวณได้พร้อมเว้นวรรค
  • ขึ้นบรรทัดใหม่เมื่อจบแต่ละแถว

แผนภาพการทำงาน

ปรับปรุงล่าสุด