CUDA Samples: image normalize(mean/standard deviation)
生活随笔
收集整理的這篇文章主要介紹了
CUDA Samples: image normalize(mean/standard deviation)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
以下CUDA sample是分別用C++和CUDA實(shí)現(xiàn)的通過均值和標(biāo)準(zhǔn)差對(duì)圖像進(jìn)行類似歸一化的操作,并對(duì)其中使用到的CUDA函數(shù)進(jìn)行了解說,各個(gè)文件內(nèi)容如下:
關(guān)于均值和標(biāo)準(zhǔn)差的計(jì)算公式可參考:?http://blog.csdn.net/fengbingchun/article/details/73323475
funset.cpp:?
#include "funset.hpp"
#include <random>
#include <iostream>
#include <vector>
#include <memory>
#include <string>
#include <algorithm>
#include "common.hpp"
#include <opencv2/opencv.hpp>int test_image_normalize()
{std::string image_name{ "E:/GitCode/CUDA_Test/test_images/lena.png" };cv::Mat matSrc = cv::imread(image_name);if (!matSrc.data) {fprintf(stderr, "read image fail: %s\n", image_name.c_str());return -1;}const int width{ 511 }, height{ 473 }, channels{ 3 };cv::resize(matSrc, matSrc, cv::Size(width, height));matSrc.convertTo(matSrc, CV_32FC3);std::vector<cv::Mat> matSplit;cv::split(matSrc, matSplit);CHECK(matSplit.size() == channels);std::unique_ptr<float[]> data(new float[matSplit[0].cols * matSplit[0].rows * channels]);size_t length{ matSplit[0].cols * matSplit[0].rows * sizeof(float) };for (int i = 0; i < channels; ++i) {memcpy(data.get() + matSplit[0].cols * matSplit[0].rows * i, matSplit[i].data, length);}float elapsed_time1{ 0.f }, elapsed_time2{ 0.f }; // millisecondsstd::unique_ptr<float[]> dst1(new float[matSplit[0].cols * matSplit[0].rows * channels]);std::unique_ptr<float[]> dst2(new float[matSplit[0].cols * matSplit[0].rows * channels]);int ret = image_normalize_cpu(data.get(), dst1.get(), width, height, channels, &elapsed_time1);if (ret != 0) PRINT_ERROR_INFO(image_normalize_cpu);ret = image_normalize_gpu(data.get(), dst2.get(), width, height, channels, &elapsed_time2);if (ret != 0) PRINT_ERROR_INFO(image_normalize_gpu);int count{ 0 }, num{ width * height * channels };for (int i = 0; i < num; ++i) {if (fabs(dst1[i] - dst2[i]) > 0.01/*EPS_*/) {fprintf(stderr, "index: %d, val1: %f, val2: %f\n", i, dst1[i], dst2[i]);++count;}if (count > 100) return -1;}std::vector<cv::Mat> merge(channels);for (int i = 0; i < channels; ++i) {merge[i] = cv::Mat(height, width, CV_32FC1, dst2.get() + i * width * height);}cv::Mat dst3;cv::merge(merge, dst3);dst3.convertTo(dst3, CV_8UC3, 255.f);cv::imwrite("E:/GitCode/CUDA_Test/test_images/image_normalize.png", dst3);//cv::resize(matSrc, matSrc, cv::Size(width, height));//cv::imwrite("E:/GitCode/CUDA_Test/test_images/image_src.png", matSrc);fprintf(stderr, "test image normalize: cpu run time: %f ms, gpu run time: %f ms\n", elapsed_time1, elapsed_time2);return 0;
}
image_normalize.cpp:
#include "funset.hpp"
#include <vector>
#include <chrono>
#include "common.hpp"int image_normalize_cpu(const float* src, float* dst, int width, int height, int channels, float* elapsed_time)
{auto start = std::chrono::steady_clock::now();const int offset{ width * height };for (int i = 0; i < channels; ++i) {const float* p1 = src + offset * i;float* p2 = dst + offset * i;float mean{ 0.f }, sd{ 0.f };for (int t = 0; t < offset; ++t) {mean += p1[t];sd += pow(p1[t], 2.f);p2[t] = p1[t];}mean /= offset;sd /= offset;sd -= pow(mean, 2.f);sd = sqrt(sd);if (sd < EPS_) sd = 1.f;for (int t = 0; t < offset; ++t) {p2[t] = (p1[t] - mean) / sd;}}auto end = std::chrono::steady_clock::now();auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start);*elapsed_time = duration.count() * 1.0e-6;return 0;
}
image_normalize.cu:
#include "funset.hpp"
#include <iostream>
#include <memory>
#include <algorithm>
#include <cmath>
#include <cuda_runtime.h> // For the CUDA runtime routines (prefixed with "cuda_")
#include <device_launch_parameters.h>
#include "common.hpp"/* __global__: 函數(shù)類型限定符;在設(shè)備上運(yùn)行;在主機(jī)端調(diào)用,計(jì)算能力3.2及以上可以在
設(shè)備端調(diào)用;聲明的函數(shù)的返回值必須是void類型;對(duì)此類型函數(shù)的調(diào)用是異步的,即在
設(shè)備完全完成它的運(yùn)行之前就返回了;對(duì)此類型函數(shù)的調(diào)用必須指定執(zhí)行配置,即用于在
設(shè)備上執(zhí)行函數(shù)時(shí)的grid和block的維度,以及相關(guān)的流(即插入<<< >>>運(yùn)算符);
a kernel,表示此函數(shù)為內(nèi)核函數(shù)(運(yùn)行在GPU上的CUDA并行計(jì)算函數(shù)稱為kernel(內(nèi)核函
數(shù)),內(nèi)核函數(shù)必須通過__global__函數(shù)類型限定符定義);*/
__global__ static void image_normalize(const float* src, float* dst, int count, int offset)
{/* gridDim: 內(nèi)置變量,用于描述線程網(wǎng)格的維度,對(duì)于所有線程塊來說,這個(gè)變量是一個(gè)常數(shù),用來保存線程格每一維的大小,即每個(gè)線程格中線程塊的數(shù)量.一個(gè)grid最多只有二維,為dim3類型;blockDim: 內(nèi)置變量,用于說明每個(gè)block的維度與尺寸.為dim3類型,包含了block在三個(gè)維度上的尺寸信息;對(duì)于所有線程塊來說,這個(gè)變量是一個(gè)常數(shù),保存的是線程塊中每一維的線程數(shù)量;blockIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程塊的索引;用于說明當(dāng)前thread所在的block在整個(gè)grid中的位置,blockIdx.x取值范圍是[0,gridDim.x-1],blockIdx.y取值范圍是[0, gridDim.y-1].為uint3類型,包含了一個(gè)block在grid中各個(gè)維度上的索引信息;threadIdx: 內(nèi)置變量,變量中包含的值就是當(dāng)前執(zhí)行設(shè)備代碼的線程索引;用于說明當(dāng)前thread在block中的位置;如果線程是一維的可獲取threadIdx.x,如果是二維的還可獲取threadIdx.y,如果是三維的還可獲取threadIdx.z;為uint3類型,包含了一個(gè)thread在block中各個(gè)維度的索引信息 */int index = threadIdx.x + blockIdx.x * blockDim.x;if (index > count - 1) return;const float* input = src + index * offset;float* output = dst + index * offset;float mean{ 0.f }, sd{ 0.f };for (size_t i = 0; i < offset; ++i) {mean += input[i];sd += pow(input[i], 2.f);output[i] = input[i];}mean /= offset;sd /= offset;sd -= pow(mean, 2.f);sd = sqrt(sd);if (sd < EPS_) sd = 1.f;for (size_t i = 0; i < offset; ++i) {output[i] = (input[i] - mean) / sd;}
}int image_normalize_gpu(const float* src, float* dst, int width, int height, int channels, float* elapsed_time)
{/* cudaEvent_t: CUDA event types,結(jié)構(gòu)體類型, CUDA事件,用于測量GPU在某個(gè)任務(wù)上花費(fèi)的時(shí)間,CUDA中的事件本質(zhì)上是一個(gè)GPU時(shí)間戳,由于CUDA事件是在GPU上實(shí)現(xiàn)的,因此它們不適于對(duì)同時(shí)包含設(shè)備代碼和主機(jī)代碼的混合代碼計(jì)時(shí) */cudaEvent_t start, stop;// cudaEventCreate: 創(chuàng)建一個(gè)事件對(duì)象,異步啟動(dòng)cudaEventCreate(&start);cudaEventCreate(&stop);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),start記錄起始時(shí)間cudaEventRecord(start, 0);float *dev_src{ nullptr }, *dev_dst{ nullptr };size_t length{ width * height * channels * sizeof(float) };// cudaMalloc: 在設(shè)備端分配內(nèi)存cudaMalloc(&dev_src, length);cudaMalloc(&dev_dst, length);/* cudaMemcpy: 在主機(jī)端和設(shè)備端拷貝數(shù)據(jù),此函數(shù)第四個(gè)參數(shù)僅能是下面之一:(1). cudaMemcpyHostToHost: 拷貝數(shù)據(jù)從主機(jī)端到主機(jī)端(2). cudaMemcpyHostToDevice: 拷貝數(shù)據(jù)從主機(jī)端到設(shè)備端(3). cudaMemcpyDeviceToHost: 拷貝數(shù)據(jù)從設(shè)備端到主機(jī)端(4). cudaMemcpyDeviceToDevice: 拷貝數(shù)據(jù)從設(shè)備端到設(shè)備端(5). cudaMemcpyDefault: 從指針值自動(dòng)推斷拷貝數(shù)據(jù)方向,需要支持統(tǒng)一虛擬尋址(CUDA6.0及以上版本)cudaMemcpy函數(shù)對(duì)于主機(jī)是同步的 */cudaMemcpy(dev_src, src, length, cudaMemcpyHostToDevice);/* <<< >>>: 為CUDA引入的運(yùn)算符,指定線程網(wǎng)格和線程塊維度等,傳遞執(zhí)行參數(shù)給CUDA編譯器和運(yùn)行時(shí)系統(tǒng),用于說明內(nèi)核函數(shù)中的線程數(shù)量,以及線程是如何組織的;尖括號(hào)中這些參數(shù)并不是傳遞給設(shè)備代碼的參數(shù),而是告訴運(yùn)行時(shí)如何啟動(dòng)設(shè)備代碼,傳遞給設(shè)備代碼本身的參數(shù)是放在圓括號(hào)中傳遞的,就像標(biāo)準(zhǔn)的函數(shù)調(diào)用一樣;不同計(jì)算能力的設(shè)備對(duì)線程的總數(shù)和組織方式有不同的約束;必須先為kernel中用到的數(shù)組或變量分配好足夠的空間,再調(diào)用kernel函數(shù),否則在GPU計(jì)算時(shí)會(huì)發(fā)生錯(cuò)誤,例如越界等;使用運(yùn)行時(shí)API時(shí),需要在調(diào)用的內(nèi)核函數(shù)名與參數(shù)列表直接以<<<Dg,Db,Ns,S>>>的形式設(shè)置執(zhí)行配置,其中:Dg是一個(gè)dim3型變量,用于設(shè)置grid的維度和各個(gè)維度上的尺寸.設(shè)置好Dg后,grid中將有Dg.x*Dg.y個(gè)block,Dg.z必須為1;Db是一個(gè)dim3型變量,用于設(shè)置block的維度和各個(gè)維度上的尺寸.設(shè)置好Db后,每個(gè)block中將有Db.x*Db.y*Db.z個(gè)thread;Ns是一個(gè)size_t型變量,指定各塊為此調(diào)用動(dòng)態(tài)分配的共享存儲(chǔ)器大小,這些動(dòng)態(tài)分配的存儲(chǔ)器可供聲明為外部數(shù)組(extern __shared__)的其他任何變量使用;Ns是一個(gè)可選參數(shù),默認(rèn)值為0;S為cudaStream_t類型,用于設(shè)置與內(nèi)核函數(shù)關(guān)聯(lián)的流.S是一個(gè)可選參數(shù),默認(rèn)值0. */image_normalize << < channels, 512 >> >(dev_src, dev_dst, channels, width*height);cudaMemcpy(dst, dev_dst, length, cudaMemcpyDeviceToHost);// cudaFree: 釋放設(shè)備上由cudaMalloc函數(shù)分配的內(nèi)存cudaFree(dev_src);cudaFree(dev_dst);// cudaEventRecord: 記錄一個(gè)事件,異步啟動(dòng),stop記錄結(jié)束時(shí)間cudaEventRecord(stop, 0);// cudaEventSynchronize: 事件同步,等待一個(gè)事件完成,異步啟動(dòng)cudaEventSynchronize(stop);// cudaEventElapseTime: 計(jì)算兩個(gè)事件之間經(jīng)歷的時(shí)間,單位為毫秒,異步啟動(dòng)cudaEventElapsedTime(elapsed_time, start, stop);// cudaEventDestroy: 銷毀事件對(duì)象,異步啟動(dòng)cudaEventDestroy(start);cudaEventDestroy(stop);return 0;
}
原圖如下:
結(jié)果圖如下:
執(zhí)行結(jié)果如下:由運(yùn)行時(shí)間可知,GPU要遠(yuǎn)慢于CPU,后面再對(duì)GPU實(shí)現(xiàn)進(jìn)行優(yōu)化。還有一個(gè)問題是,在Release下,執(zhí)行正常,在Debug下,GPU,在調(diào)用核函數(shù)時(shí),會(huì)在for循環(huán)中無故退出,具體原因還未知,后面待進(jìn)一步分析。
GitHub:?https://github.com/fengbingchun/CUDA_Test
總結(jié)
以上是生活随笔為你收集整理的CUDA Samples: image normalize(mean/standard deviation)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CUDA Samples: 获取设备属性
- 下一篇: CUDA Samples: approx