supermaca

Untitled

Oct 13th, 2023
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <cstdint>
  5.  
  6. uint32_t swap_endian(uint32_t val) {
  7.     return ((val << 24) & 0xff000000) |
  8.            ((val <<  8) & 0x00ff0000) |
  9.            ((val >>  8) & 0x0000ff00) |
  10.            ((val >> 24) & 0x000000ff);
  11. }
  12.  
  13. void read_mnist_images(const std::string& filepath) {
  14.     std::ifstream file(filepath, std::ios::binary);
  15.     if (file.is_open()) {
  16.         uint32_t magic, num_imgs, rows, cols;
  17.         file.read(reinterpret_cast<char*>(&magic), 4);
  18.         file.read(reinterpret_cast<char*>(&num_imgs), 4);
  19.         file.read(reinterpret_cast<char*>(&rows), 4);
  20.         file.read(reinterpret_cast<char*>(&cols), 4);
  21.  
  22.         magic = swap_endian(magic);
  23.         num_imgs = swap_endian(num_imgs);
  24.         rows = swap_endian(rows);
  25.         cols = swap_endian(cols);
  26.  
  27.         // Navigate to the image at index 5
  28.         file.seekg(16 + 5 * rows * cols, std::ios::beg);
  29.  
  30.         // Read and print image at IDX=5
  31.         std::vector<uint8_t> image(rows * cols);
  32.         file.read(reinterpret_cast<char*>(&image[0]), rows * cols);
  33.  
  34.         std::cout << "Image at IDX=5:" << std::endl;
  35.         for(int r = 0; r < rows; ++r) {
  36.             for(int c = 0; c < cols; ++c) {
  37.                 std::cout << static_cast<int>(image[r * cols + c]) << ' ';
  38.             }
  39.             std::cout << std::endl;
  40.         }
  41.  
  42.     } else {
  43.         std::cout << "Error opening file." << std::endl;
  44.     }
  45. }
  46.  
  47. void read_mnist_labels(const std::string& filepath) {
  48.     std::ifstream file(filepath, std::ios::binary);
  49.     if (file.is_open()) {
  50.         uint32_t magic, num_labels;
  51.         file.read(reinterpret_cast<char*>(&magic), 4);
  52.         file.read(reinterpret_cast<char*>(&num_labels), 4);
  53.  
  54.         magic = swap_endian(magic);
  55.         num_labels = swap_endian(num_labels);
  56.  
  57.         // Navigate to the label at index 5
  58.         file.seekg(8 + 5, std::ios::beg);
  59.  
  60.         // Read and print label at IDX=5
  61.         uint8_t label;
  62.         file.read(reinterpret_cast<char*>(&label), 1);
  63.  
  64.         std::cout << "Label at IDX=5: " << static_cast<int>(label) << std::endl;
  65.  
  66.     } else {
  67.         std::cout << "Error opening file." << std::endl;
  68.     }
  69. }
  70.  
  71. int main() {
  72.     read_mnist_images("train-images.idx3-ubyte");
  73.     read_mnist_labels("train-labels.idx1-ubyte");
  74.     return 0;
  75. }
Add Comment
Please, Sign In to add comment