| 14 | //遍历该目录下的.jpg图片 |
| 15 | void load_data_from_folder(std::string path, std::string type, std::vector<std::string> &list_images, std::vector<int> &list_labels, int label); |
| 16 | class myDataset:public torch::data::Dataset<myDataset>{ |
| 17 | public: |
| 18 | int num_classes = 0; |
| 19 | myDataset(std::string image_dir, std::string type){ |
| 20 | load_data_from_folder(image_dir, std::string(type), image_paths, labels, num_classes); |
| 21 | } |
| 22 | // Override get() function to return tensor at location index |
| 23 | torch::data::Example<> get(size_t index) override{ |
| 24 | std::string image_path = image_paths.at(index); |
| 25 | cv::Mat image = cv::imread(image_path); |
| 26 | cv::resize(image, image, cv::Size(224, 224)); |
| 27 | int label = labels.at(index); |
| 28 | torch::Tensor img_tensor = torch::from_blob(image.data, { image.rows, image.cols, 3 }, torch::kByte).permute({ 2, 0, 1 }); // Channels x Height x Width |
| 29 | torch::Tensor label_tensor = torch::full({ 1 }, label); |
| 30 | return {img_tensor.clone(), label_tensor.clone()}; |
| 31 | } |
| 32 | // Return the length of data |
| 33 | torch::optional<size_t> size() const override { |
| 34 | return image_paths.size(); |
| 35 | }; |
| 36 | private: |
| 37 | std::vector<std::string> image_paths; |
| 38 | std::vector<int> labels; |
| 39 | }; |