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

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

相关推荐
我真的是大笨蛋4 小时前
K8S-Pod(下)
java·笔记·云原生·容器·kubernetes
碳水加碳水4 小时前
Java代码审计实战:XML外部实体注入(XXE)深度解析
java·安全·web安全·代码审计
努力也学不会java5 小时前
【设计模式】 原型模式
java·设计模式·原型模式
方渐鸿6 小时前
【2024】k8s集群 图文详细 部署安装使用(两万字)
java·运维·容器·kubernetes·k8s·运维开发·持续部署
学亮编程手记6 小时前
K8S v1.33 版本主要新特性介绍
java·容器·kubernetes
Haven-7 小时前
Java-面试八股文-JVM篇
java·jvm·面试
我真的是大笨蛋7 小时前
JVM调优总结
java·jvm·数据库·redis·缓存·性能优化·系统架构
wjs0407 小时前
Git常用的命令
java·git·gitlab
superlls7 小时前
(算法 哈希表)【LeetCode 349】两个数组的交集 思路笔记自留
java·数据结构·算法
honder试试8 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python