Java图像通道顺序变换(rgb转为bgr)
程序员文章站
2022-04-24 15:07:09
...
Java图像通道顺序变换(rgb转为bgr)
原理:要使得rgb和bgr互换,只需调换r和b通道。Java中借助BufferedImage
进行转化,详见代码。
效果:
代码:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class RGB2BGR {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("d:\\rgb.jpg");
byte[] imgBytes = new byte[fileInputStream.available()];
fileInputStream.read(imgBytes);
fileInputStream.close();
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imgBytes));
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
// 获取图片中每个rgb像素的int类型表示
int[] rgbPixels = bufferedImage.getRGB(0, 0, width, height, null, 0, width);
int[] bgrPixels = new int[rgbPixels.length];
for (int i = 0; i < rgbPixels.length; i++) {
int color = rgbPixels[i];
int red = ((color & 0x00FF0000) >> 16);
int green = ((color & 0x0000FF00) >> 8);
int blue = color & 0x000000FF;
// 将rgb三个通道的数值合并为一个int数值,同时调换b通道和r通道
bgrPixels[i] = (red & 0x000000FF) | (green << 8 & 0x0000FF00) | (blue << 16 & 0x00FF0000);
}
bufferedImage.setRGB(0, 0, width, height, bgrPixels, 0, width);
ImageIO.write(bufferedImage, "jpg", new File("d:\\bgr.jpg"));
}
}
python代码
import cv2
img = cv2.imread('d:\\rgb.jpg')
img = img[:,:, (2, 1, 0)]
cv2.imwrite('d:\\bgr.jpg',img)
Java vs Python 代码量
Life is short, you need Python
参考文章:
https://www.cnblogs.com/roucheng/p/3527655.html
https://blog.csdn.net/river66/article/details/89514816
思路来源:
走过的弯路:ColorConvertOp
只能在不同颜色空间之间相互转换,rgb和bgr都属于ColorSpace.CS_sRGB
(可以调试观察BufferedImage
的各个属性值),所以下面的转换是失败的,转换后的图片和转换前是一样的,因为都是同个颜色空间,所以底层只是做了复制,具体可以查看源码。
// 转RGB格式
// 参考:https://www.zhangshengrong.com/p/2EaE0rPR1M/
BufferedImage rgbImage = new BufferedImage(bgrImage.getWidth(), bgrImage.getHeight(), bgrImage.TYPE_3BYTE_BGR);
new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(bgrImage, rgbImage);
ImageIO.write(rgbImage, "jpg", new File("d:\\rgb.jpg"));
上一篇: PHP之AJAX
下一篇: 分享一个常用的生成唯一订单号方法