使用GPU进行图像拼接加速遇到的问题

232 阅读1分钟

由于一次性需要拼接大量图片,采用多线程一次性拼接一定数量的图片:

@Override
public void run() {
    //从第几张图片开始拼接
    int index = i * 5;
    UMatVector images;
    if (index + 5 <= fileList.length) {
        //如果有5张图片,则创建容量为5的容器
        images = new UMatVector(5);
    } else {
        //如果是最后一张,直接输出,不进入拼接程序
        if (fileList.length - index == 1) {
            if (this.i < 10) {
                imwrite("D:\cvtest4\D00" + this.i + ".jpg", imread(fileList[fileList.length - 1].getAbsolutePath()));
            }
            if (this.i < 100 && this.i >= 10) {
                imwrite("D:\cvtest4\D0" + this.i + ".jpg", imread(fileList[fileList.length - 1].getAbsolutePath()));
            }
            if (this.i >= 100) {
                imwrite("D:\cvtest4\D" + this.i + ".jpg", imread(fileList[fileList.length - 1].getAbsolutePath()));
            }
            return;
        }
        //如果小于5张图片,创建对应大小的容器
        images = new UMatVector(fileList.length - index);
    }
    System.out.println(Thread.currentThread().getName() + "-start:......");
    //加载每张图片
    for (int j = 0; j < 5; j++) {
        if (index + j + 1 > fileList.length) {
            continue;
        }
        uImage = imread(fileList[j + index].getAbsolutePath()).getUMat(ACCESS_FAST);
        images.put(j, uImage);
        uImage.release();
    }
    //创建拼接工具
    Stitcher stitcher = Stitcher.create();
    stitcher.setWaveCorrection(false);//关闭波纹校正
    //进行拼接
    int i = stitcher.stitch(images, uImage);
    if (i != 0) {
        //拼接失败的图片再拼接一次
        stitcher.stitch(images, uImage);
    }
    image = uImage.getMat(ACCESS_FAST);
    //释放内存
    stitcher.close();
    //输出图像
    if (this.i < 10) {
        imwrite("D:\cvtest4\D00" + this.i + ".jpg", image);
    }
    if (this.i < 100 && this.i >= 10) {
        imwrite("D:\cvtest4\D0" + this.i + ".jpg", image);
    }
    if (this.i >= 100) {
        imwrite("D:\cvtest4\D" + this.i + ".jpg", image);
    }
    //释放Mat对象
    images.close();
    image.release();
    uImage.release();
}

加载图片之后得到的是opencv中的Mat类型对象,通过getMat方法得到UMat对象,它是一种跨平台的数据结构,可以在CPU和GPU之间共享数据,使用UMatVector对象来装UMat对象,通过Stitcher对象传入UMatVector对象进行拼接,但是在执行了一段时间后会报错:

1.png

查百度说的是UMat对象使用完了之后必须进行释放,这个错误是还有UMat关联的对象未进行释放,现在尝试优化代码释放UMat及其所有关联对象,还有加入多线程之后一次性加入的线程过多好像也会直接报这个错,也需要尝试并修改... ...