使用CV_CUDA对图像进行Crop和Resize

2023-11-08 15:30

本文主要是介绍使用CV_CUDA对图像进行Crop和Resize,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

可能是我的使用方式不对,直接调用C++ OpenCV api比用CV_CUDA快很多。

/** SPDX-FileCopyrightText: Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.* SPDX-License-Identifier: Apache-2.0** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/#include <common/NvDecoder.h>
#include <common/TestUtils.h>
#include <cuda_runtime_api.h>
#include <cvcuda/OpCustomCrop.hpp>
#include <cvcuda/OpResize.hpp>
#include <getopt.h>
#include <cmath>
#include <opencv2/opencv.hpp>
#include <nvcv/Image.hpp>
#include <nvcv/Tensor.hpp>#include <chrono>   
using namespace std;
using namespace chrono;
/*** @brief Crop and Resize sample app.** The Crop and Resize is a simple pipeline which demonstrates usage of* CVCuda Tensor along with a few operators.** Input Batch Tensor -> Crop -> Resize -> WriteImage*//*** @brief Utility to show usage of sample app***/
void showUsage()
{std::cout << "usage: ./nvcv_cropandresize_app -i <image file path or  image directory -b <batch size>" << std::endl;
}/*** @brief Utility to parse the command line arguments***/
int ParseArgs(int argc, char *argv[], std::string &imagePath, uint32_t &batchSize)
{static struct option long_options[] = {{     "help",       no_argument, 0, 'h'},{"imagePath", required_argument, 0, 'i'},{    "batch", required_argument, 0, 'b'},{          0,                 0, 0,   0}};int long_index = 0;int opt        = 0;while ((opt = getopt_long(argc, argv, "hi:b:", long_options, &long_index)) != -1){switch (opt){case 'h':showUsage();return -1;break;case 'i':imagePath = optarg;break;case 'b':batchSize = std::stoi(optarg);break;case ':':showUsage();return -1;default:break;}}std::ifstream imageFile(imagePath);if (!imageFile.good()){showUsage();std::cerr << "Image path '" + imagePath + "' does not exist\n";return -1;}return 0;
}int main(int argc, char *argv[])
{// Default parametersstd::string imagePath = "test.jpg";uint32_t    batchSize = 1;cv::Mat imgMat = cv::imread(imagePath);// Parse the command line paramaters to override the default parametersint retval = ParseArgs(argc, argv, imagePath, batchSize);if (retval != 0){return retval;}// NvJpeg is used to decode the images to the color format required.// Since we need a contiguous buffer for batched input, a buffer is// preallocated based on the  maximum image dimensions and  batch size// for NvJpeg to write into.// Note : The maximum input image dimensions needs to be updated in case// of testing with different test imagesint maxImageWidth  = 1920;int maxImageHeight = 1080;int maxChannels    = 3;// tag: Create the cuda streamcudaStream_t stream;CHECK_CUDA_ERROR(cudaStreamCreate(&stream));// tag: Allocate input tensor// Allocating memory for RGBI input image batch of uint8_t data type// without padding since NvDecode utility currently doesnt support// Padded buffers.nvcv::TensorDataStridedCuda::Buffer inBuf;inBuf.strides[3] = sizeof(uint8_t);inBuf.strides[2] = maxChannels * inBuf.strides[3];inBuf.strides[1] = maxImageWidth * inBuf.strides[2];inBuf.strides[0] = maxImageHeight * inBuf.strides[1];CHECK_CUDA_ERROR(cudaMallocAsync(&inBuf.basePtr, batchSize * inBuf.strides[0], stream));// tag: Tensor Requirements// Calculate the requirements for the RGBI uint8_t Tensor which include// pitch bytes, alignment, shape  and tensor layoutnvcv::Tensor::Requirements inReqs= nvcv::Tensor::CalcRequirements(batchSize, {maxImageWidth, maxImageHeight}, nvcv::FMT_RGB8);// Create a tensor buffer to store the data pointer and pitch bytes for each planenvcv::TensorDataStridedCuda inData(nvcv::TensorShape{inReqs.shape, inReqs.rank, inReqs.layout},nvcv::DataType{inReqs.dtype}, inBuf);// TensorWrapData allows for interoperation of external tensor representations with CVCUDA Tensor.nvcv::Tensor inTensor = nvcv::TensorWrapData(inData);// tag: Image Loading// NvJpeg is used to load the images to create a batched input device buffer.uint8_t             *gpuInput = reinterpret_cast<uint8_t *>(inBuf.basePtr);CHECK_CUDA_ERROR(cudaMemcpyAsync(gpuInput, imgMat.data, inBuf.strides[0], cudaMemcpyHostToDevice));// The total images is set to the same value as batch size for testinguint32_t             totalImages = batchSize;// Format in which the decoded output will be saved//nvjpegOutputFormat_t outputFormat = NVJPEG_OUTPUT_RGBI;//NvDecode(imagePath, batchSize, totalImages, outputFormat, gpuInput);// tag: The input buffer is now ready to be used by the operators// Set parameters for Crop and Resize// ROI dimensions to crop in the input imageint cropX      = 150;int cropY      = 50;int cropWidth  = 800;int cropHeight = 1000;// Set the resize dimensionsint resizeWidth  = 1600;int resizeHeight = 2000;//  Initialize the CVCUDA ROI structNVCVRectI crpRect = {cropX, cropY, cropWidth, cropHeight};cv::Rect Rect(cropX, cropY, cropWidth, cropHeight);auto t1=std::chrono::steady_clock::now();// 裁剪图像cv::Mat cropImg = imgMat(Rect);// 调整图像大小cv::resize(cropImg, cropImg, cv::Size(resizeWidth, resizeHeight));auto t2=std::chrono::steady_clock::now();double dr_ms=std::chrono::duration<double,std::milli>(t2-t1).count();std::cout << "opencv costs: " <<  dr_ms << "ms" << std::endl;// tag: Allocate Tensors for Crop and Resize// Create a CVCUDA Tensor based on the crop window size.nvcv::Tensor cropTensor(batchSize, {cropWidth, cropHeight}, nvcv::FMT_RGB8);// Create a CVCUDA Tensor based on resize dimensionsnvcv::Tensor resizedTensor(batchSize, {resizeWidth, resizeHeight}, nvcv::FMT_RGB8);// tag: Initialize operators for Crop and Resizecvcuda::CustomCrop cropOp;cvcuda::Resize     resizeOp;cudaEvent_t start, stop;cudaEventCreate(&start);cudaEventCreate(&stop);cudaEventRecord(start);// tag: Executes the CustomCrop operation on the given cuda streamcropOp(stream, inTensor, cropTensor, crpRect);// Resize operator can now be enqueued into the same streamresizeOp(stream, cropTensor, resizedTensor, NVCV_INTERP_LINEAR);// tag: Profile sectioncudaEventRecord(stop);cudaEventSynchronize(stop);float operatorms = 0;cudaEventElapsedTime(&operatorms, start, stop);std::cout << "Time for Crop and Resize : " << operatorms << " ms" << std::endl;// tag: Copy the buffer to CPU and write resized image into .bmp fileWriteRGBITensor(resizedTensor, stream);// tag: Clean upCHECK_CUDA_ERROR(cudaStreamDestroy(stream));// tag: End of Sample
}

输出

opencv costs: 3.16336ms
Time for Crop and Resize : 200.148 ms
Writing to ./cvcudatest_0.jpg 4800 1600 2000

这篇关于使用CV_CUDA对图像进行Crop和Resize的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/370785

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景