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;
	}

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

相关推荐
Java爱好狂.18 小时前
Redis高级笔记:深入浅出Java面试高频考点!
java·数据库·redis·后端·java面试·java程序员·java八股文
会编程的土豆18 小时前
Go 里 interface 为什么能比较?到底在比什么?
开发语言·后端·golang
罗超驿18 小时前
10.滑动窗口解决:无重复字符的最长子串 | LeetCode 3 Java 题解
java·算法·leetcode·面试
nnsix18 小时前
MVC、MVP、MVVM 架构 笔记
java·开发语言·前端
野生技术架构师18 小时前
2026最新Java面试1200题全解析:从基础到架构,覆盖所有技术栈(含答案)
java·面试·架构
大尚来也18 小时前
主键、外键、索引,一篇讲透
java·数据库·oracle
Smile_25422041818 小时前
vue3 + ts reactive方式清空表单对象
开发语言·前端·javascript
段ヤシ.18 小时前
回顾Java知识点,面试题汇总Day17(持续更新)
java·springboot·spring security·shiro·mybatis-plus·jdbctemplate·spring data jpa
jjjava2.018 小时前
Java 多线程核心基础与线程安全
java·开发语言
悟乙己18 小时前
因果推断方法实践:Python实现合成控制法
开发语言·python