使用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

相关文章

详解Vue如何使用xlsx库导出Excel文件

《详解Vue如何使用xlsx库导出Excel文件》第三方库xlsx提供了强大的功能来处理Excel文件,它可以简化导出Excel文件这个过程,本文将为大家详细介绍一下它的具体使用,需要的小伙伴可以了解... 目录1. 安装依赖2. 创建vue组件3. 解释代码在Vue.js项目中导出Excel文件,使用第三

Linux alias的三种使用场景方式

《Linuxalias的三种使用场景方式》文章介绍了Linux中`alias`命令的三种使用场景:临时别名、用户级别别名和系统级别别名,临时别名仅在当前终端有效,用户级别别名在当前用户下所有终端有效... 目录linux alias三种使用场景一次性适用于当前用户全局生效,所有用户都可调用删除总结Linux

java图像识别工具类(ImageRecognitionUtils)使用实例详解

《java图像识别工具类(ImageRecognitionUtils)使用实例详解》:本文主要介绍如何在Java中使用OpenCV进行图像识别,包括图像加载、预处理、分类、人脸检测和特征提取等步骤... 目录前言1. 图像识别的背景与作用2. 设计目标3. 项目依赖4. 设计与实现 ImageRecogni

python管理工具之conda安装部署及使用详解

《python管理工具之conda安装部署及使用详解》这篇文章详细介绍了如何安装和使用conda来管理Python环境,它涵盖了从安装部署、镜像源配置到具体的conda使用方法,包括创建、激活、安装包... 目录pytpshheraerUhon管理工具:conda部署+使用一、安装部署1、 下载2、 安装3

Mysql虚拟列的使用场景

《Mysql虚拟列的使用场景》MySQL虚拟列是一种在查询时动态生成的特殊列,它不占用存储空间,可以提高查询效率和数据处理便利性,本文给大家介绍Mysql虚拟列的相关知识,感兴趣的朋友一起看看吧... 目录1. 介绍mysql虚拟列1.1 定义和作用1.2 虚拟列与普通列的区别2. MySQL虚拟列的类型2

使用MongoDB进行数据存储的操作流程

《使用MongoDB进行数据存储的操作流程》在现代应用开发中,数据存储是一个至关重要的部分,随着数据量的增大和复杂性的增加,传统的关系型数据库有时难以应对高并发和大数据量的处理需求,MongoDB作为... 目录什么是MongoDB?MongoDB的优势使用MongoDB进行数据存储1. 安装MongoDB

关于@MapperScan和@ComponentScan的使用问题

《关于@MapperScan和@ComponentScan的使用问题》文章介绍了在使用`@MapperScan`和`@ComponentScan`时可能会遇到的包扫描冲突问题,并提供了解决方法,同时,... 目录@MapperScan和@ComponentScan的使用问题报错如下原因解决办法课外拓展总结@

mysql数据库分区的使用

《mysql数据库分区的使用》MySQL分区技术通过将大表分割成多个较小片段,提高查询性能、管理效率和数据存储效率,本文就来介绍一下mysql数据库分区的使用,感兴趣的可以了解一下... 目录【一】分区的基本概念【1】物理存储与逻辑分割【2】查询性能提升【3】数据管理与维护【4】扩展性与并行处理【二】分区的

使用Python实现在Word中添加或删除超链接

《使用Python实现在Word中添加或删除超链接》在Word文档中,超链接是一种将文本或图像连接到其他文档、网页或同一文档中不同部分的功能,本文将为大家介绍一下Python如何实现在Word中添加或... 在Word文档中,超链接是一种将文本或图像连接到其他文档、网页或同一文档中不同部分的功能。通过添加超

Linux使用fdisk进行磁盘的相关操作

《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存