java 抠取红色印章(透明背景)

一个亲戚让我帮他把照片里的红色印章抠出来,,,记录下处理过程,代码如下,可直接用:

复制代码
public static void signatureProcess(String sourceImagePath, String targetImagePath) {
		Graphics2D graphics2D = null;
		try {
			File imageFile = new File(sourceImagePath);
			BufferedImage sourceBufferIamge = ImageIO.read(imageFile);
			//新图大小与原图保持一致
			int targetImageWidth = sourceBufferIamge.getWidth();
			int targetImageHeight = sourceBufferIamge.getHeight();

			BufferedImage targetBufferImage = new BufferedImage(targetImageWidth, targetImageHeight, BufferedImage.TYPE_4BYTE_ABGR);
			graphics2D = targetBufferImage.createGraphics();
			graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

			int targetW = targetBufferImage.getWidth();
			int targetH = targetBufferImage.getHeight();
			int targetMinX = targetBufferImage.getMinX();
			int targetMinY = targetBufferImage.getMinY();

			for (int i = targetMinX; i < targetW; i++) {
				for (int j = targetMinY; j < targetH; j++) {
					// 得到原图像素(i,j)上的RGB值
					int pixel = sourceBufferIamge.getRGB(i, j);
					Color color = new Color(pixel);
					float[] hsbvals=new float[3];
					float[] floats = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), hsbvals);

					int red = (pixel >> 16) & 0xFF;

					// 判断是否为红色印章
					if (red > 200 && colorInRange(floats)) { //双重判断,精细一点 可以根据需要调整阈值
						targetBufferImage.setRGB(i, j, pixel);
					} else {
						// 不是红色,设置为透明
						targetBufferImage.setRGB(i, j, 0x00000000);
					}
				}
			}
			// 保存到新文件
			FileOutputStream ops = new FileOutputStream(new File(targetImagePath));
			ImageIO.write(targetBufferImage, "png", ops);
			ops.flush();
			ops.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if (graphics2D != null) {
				graphics2D.dispose();
			}
		}
	}

	private static Boolean colorInRange( float[] floats){
		if (0.90< floats[0]) {
			return true;
		}
		return false;
	}

运行效果(章名打了马赛克),左变为抠出的章,右边为原图,如果抠图效果不好,调整代码判断阈值,最好选清晰的色差大的抠图:

相关推荐
Mr.每天进步一小步7 分钟前
每天记录一道Java面试题---day39
java·jvm·面试
工业互联网专业8 分钟前
基于springboot+vue的数码产品抢购系统
java·vue.js·spring boot·毕业设计·源码·课程设计·数码产品抢购系统
敖云岚9 分钟前
【AI】SpringAI 第二弹:接入 DeepSeek 官方服务
java·人工智能·spring boot·后端·spring
purrrew12 分钟前
【数据结构_6】双向链表的实现
java·数据结构·链表
古月居GYH15 分钟前
嵌入式C语言高级编程:OOP封装、TDD测试与防御性编程实践
c语言·开发语言·tdd
nangonghen18 分钟前
JAVA程序实现mysql读写分离并在kubernetes中演示
java·mysql·mybatis·读写分离
ghost14321 分钟前
Python自学第1天:变量,打印,类型转化
开发语言·python·学习
eternal__day23 分钟前
MyBatis-Plus 详解:快速上手到深入理解
java·spring boot·后端·spring·java-ee·maven·mybatis
Java中文社群37 分钟前
超实用!用FunctionCall实现快递AI助手
java·人工智能·后端
汤姆_51138 分钟前
【c语言】深入理解指针1
c语言·开发语言