基础算法篇-获取图片中连续像素集合2

该篇主要为解决大图片递归时栈内存溢出问题。

util改进代码:

	//最大递归深度
	private static int MAX_RECURSION_DEPTH = 1000;
/**
	 * 递归读图
	 * @param image
	 * @param i
	 * @param j
	 * @param colors 存储所有元素的总集合
	 */
	public static void recursion(BufferedImage image, int i, int j, Set<ColorPo> colorsAllSet) {
		boolean flag = getBlackArrays(image,i,j,colorsAllSet,0);
		//如果为true 说明是强制返回  需要从返回点位重新筛选。
		if (flag) {
			//重定义一个替身Set,用来存储该次递归中所有的参数
			Set<ColorPo> substituteColorSet = new HashSet<ColorPo>(colorsAllSet);
			for (ColorPo colorPo : colorsAllSet) {
				recursion(image, colorPo.getX(), colorPo.getY(), substituteColorSet);
			}
			colorsAllSet.addAll(substituteColorSet);
			//清空替身内容,并回收垃圾
			substituteColorSet = null;
		}
	}

/**
	 * 获取相邻像素集合
	 * @param image
	 * @param x
	 * @param y
	 * @param colorPoSet 
	 * @param colorPoSet 
	 */
public static boolean getBlackArrays(BufferedImage image,int x,int y, Set<ColorPo> colorPoSet,int RECURSION_DEPTH) {
		//判断递归深度,超过深度则强制返回
		if (RECURSION_DEPTH > MAX_RECURSION_DEPTH) {
			return true;
		}
		ColorPo colorPo = null;
		for (int sy = 1; sy >= -1; sy--) {
			for (int sx = 1; sx >= -1; sx--) {
				if (sx == 0 ? sx == sy : false) {
					continue;
				}
				int startX = sx + x,startY = sy+y;
				if (startX >=0 && startX < image.getWidth() && startY>= 0 && startY < image.getHeight()) {
					colorPo = new ColorPo(image.getRGB(startX, startY), startX, startY);
					if (colorPo.isBlack() && !colorPoSet.contains(colorPo)) {
						colorPoSet.add(colorPo);
						boolean flag = getBlackArrays(image, startX, startY,colorPoSet,++RECURSION_DEPTH);
						//返回递归状态码
						if (flag) {
							return flag;
						}
					}
				}
			}
		}
		return false;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值