CUDA Networks
matrix_preview_image.cu
Go to the documentation of this file.
1 /**
2  * @file matrix_preview_image.cu
3  * @brief Implementation of the Matrix::preview_image method.
4  */
5 #include "matrix.h"
6 #include <cuda_runtime.h>
7 #include <iostream>
8 #include <iomanip>
9 #include <cmath>
10 
11 void Matrix::preview_image(int row_index, int image_size_x, int image_size_y) const {
12  // Check if the row_index is within the valid range
13  if (row_index < 0 || row_index >= rows) {
14  throw std::out_of_range("Invalid row index");
15  }
16 
17  // Check if the image dimensions fit within the matrix columns
18  if (image_size_x * image_size_y > cols) {
19  throw std::invalid_argument("Image dimensions exceed matrix column count");
20  }
21 
22  // Allocate host memory to store a single row of the matrix
23  double* h_data = new double[cols];
24 
25  // Copy the specified row from device (GPU) memory to host memory
26  cudaMemcpy(h_data, d_data + row_index * cols, cols * sizeof(double), cudaMemcpyDeviceToHost);
27 
28  // Iterate over each row of the image
29  for (int i = 0; i < image_size_x; ++i) {
30  // Iterate over each column of the image
31  for (int j = 0; j < image_size_y; ++j) {
32  // Calculate the index in the flattened array
33  int index = i * image_size_y + j;
34 
35  // Round the pixel value to the nearest integer
36  int value = static_cast<int>(std::round(h_data[index]));
37 
38  // Print spaces for zero values (background)
39  if (value == 0) {
40  std::cout << " ";
41  } else {
42  // Print non-zero values with 3-digit width
43  std::cout << std::setw(3) << value << " ";
44  }
45  }
46  // Move to the next line after each row of the image
47  std::cout << std::endl;
48  }
49  // Print an extra newline for separation
50  std::cout << std::endl;
51 
52  // Free the allocated host memory
53  delete[] h_data;
54 }
void preview_image(int row_index, int image_size_x, int image_size_y) const
Preview a single image from the matrix.
Defines the Matrix class for GPU-accelerated matrix operations.