0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

cufftComplexに画素値を代入してみる

Posted at

##概要

  • OpenCV C++ で読み込んだ画像を、cufftで使用するcufftComplexに渡す

##関連記事

##コード

.cpp
#include <opencv2/core/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv/cv.hpp>
#include <iostream>

#include "cufft.h"

#include <string>
#include <vector>
#include <sys/stat.h>
#include "helper_cuda.h" //省いてもok 省く場合はcheckCudaErrorsは使えない

using namespace std;

int main()
{
    //画像をグレースケールで読み込み(作業がしやすいので)
 	cv::Mat img = cv::imread("test.jpg", 0);

    if(img.empty()==true){
      cout << "Error opening file" << "("<< __LINE__<< ")" << endl;
      return 0;
    }
 
    int width, height;

    width  = img.cols;	// 横幅を取得
	height = img.rows;	// 縦幅を取得
    
    // 入力
    cufftComplex *d_i_img;
    checkCudaErrors(cudaMalloc((void **)&d_i_img, sizeof(cufftComplex)*width*height));

    // 画素値代入用変数
    cufftComplex *h_complex;
    checkCudaErrors(cudaMallocHost((void **)&h_complex, sizeof(cufftComplex)*height*width));
 
    cout << "width : "<< width << " height : " << height << endl;
 
    // 画素値代入
    for( int icnt =0;  icnt<height*width; ++icnt){ 
        h_complex[icnt].x = (float)img.data[icnt];
        h_complex[icnt].y = 0.0f;
    }
    
    checkCudaErrors(cudaMemcpy(d_i_img, h_complex, sizeof(cufftComplex)*width*height, cudaMemcpyHostToDevice));
    
    // すべてのcopyが終わるまで待機
    if (cudaDeviceSynchronize() != cudaSuccess){
      cout << "Cuda error: Failed to synchronize\n";
      return 0;
    }

    cudaFree(d_i_img);
    cudaFree(h_complex);
    cout << "ok";

    return 0;
}

解説

コードの方を少し解説しますと

GPUに入力する画像の大きさ分のメモリをcudaMallocで確保

.cpp
// 入力
cufftComplex *d_i_img;
checkCudaErrors(cudaMalloc((void **)&d_i_img, sizeof(cufftComplex)*width*height));

画素値を代入する用のcufftComplexをcudaMallocHostでホスト側にメモリを確保

.cpp
// 画素値代入用変数
cufftComplex *h_complex;
cudaMallocHost((void **)&h_complex, height * width * sizeof(cufftComplex));

その後画素値を代入

.cpp
// 画素値代入
for( int icnt =0;  icnt<height*width; ++icnt){ 
    h_complex[icnt].x = (float)img.data[icnt];
    h_complex[icnt].y = 0.0f;
}

これで画像を使ってcufftの入力に加えたりすることができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?