如何使用Java OpenCV库将彩色图像转换为棕褐色图像?
将彩色图像转换为棕褐色的算法:
获取每个像素的红、绿、蓝值
计算这三种颜色的平均值。
定义深度和强度值(理想值为20和30)。
修改值如下:
red = red + (depth*2).
Green = green +depth.
blue = blue-intensity.
确保修改后的值在0到255之间。
根据修改后的颜色创建新的像素值,并将新值设置为像素。
Java实现
使用ImageIO.read()方法读取所需的图像。
获取图像的高度和宽度。
使用嵌套for循环遍历图像中的每个像素。
使用getRGB()方法获取像素值。
将上面获取的像素值作为参数创建一个Color对象。
分别使用getRed()、getGreen()和getBlue()方法从颜色对象中获取红色、绿色和蓝色值。
根据算法中指定的计算新的红色、绿色和蓝色值。
使用修改后的RGB值创建一个新的像素。
使用setRGB()方法设置新的像素值。
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
示例
import java.io.File; import java.io.IOException; import java.awt.Color; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class Color2Sepia { public static void main(String args[])throws IOException { //Reading the image File file= new File("D:\Images\cuba.jpg"); BufferedImage img = ImageIO.read(file); for (int y = 0; y < img.getHeight(); y++) { for (int x = 0; x < img.getWidth(); x++) { //Retrieving the values of a pixel int pixel = img.getRGB(x,y); //Creating a Color object from pixel value Color color = new Color(pixel, true); //Retrieving the R G B values int red = color.getRed(); int green = color.getGreen(); int blue = color.getBlue(); int avg = (red+green+blue)/3; int depth = 20; int intensity = 30; red= avg+(depth*2); green = avg+depth; blue = avg-intensity; //Making sure that RGB values lies between 0-255 if (red > 255)red = 255; if (green > 255)green = 255; if (blue > 255)blue = 255; if (blue<0)blue=0; //Creating new Color object color = new Color(red, green, blue); //Setting new Color object to the image img.setRGB(x, y, color.getRGB()); } } //Saving the modified image file = new File("D:\Images\sepia_image2.jpg"); ImageIO.write(img, "jpg", file); System.out.println("Done..."); } }
输入
输出
广告