"vscode:/vscode.git/clone" did not exist on "8024fc5eec67c9ba9bd4df36bade64a939624ab4"
decode_image.cpp 1.58 KB
Newer Older
1
#include "decode_image.h"
2

Nicolas Hug's avatar
Nicolas Hug committed
3
#include "decode_gif.h"
4
5
6
7
8
#include "decode_jpeg.h"
#include "decode_png.h"

namespace vision {
namespace image {
Francisco Massa's avatar
Francisco Massa committed
9

10
11
12
13
torch::Tensor decode_image(
    const torch::Tensor& data,
    ImageReadMode mode,
    bool apply_exif_orientation) {
14
15
  // Check that tensor is a CPU tensor
  TORCH_CHECK(data.device() == torch::kCPU, "Expected a CPU tensor");
Francisco Massa's avatar
Francisco Massa committed
16
17
18
19
20
21
22
23
24
25
26
  // Check that the input tensor dtype is uint8
  TORCH_CHECK(data.dtype() == torch::kU8, "Expected a torch.uint8 tensor");
  // Check that the input tensor is 1-dimensional
  TORCH_CHECK(
      data.dim() == 1 && data.numel() > 0,
      "Expected a non empty 1-dimensional tensor");

  auto datap = data.data_ptr<uint8_t>();

  const uint8_t jpeg_signature[3] = {255, 216, 255}; // == "\xFF\xD8\xFF"
  const uint8_t png_signature[4] = {137, 80, 78, 71}; // == "\211PNG"
Nicolas Hug's avatar
Nicolas Hug committed
27
28
29
30
  const uint8_t gif_signature_1[6] = {
      0x47, 0x49, 0x46, 0x38, 0x39, 0x61}; // == "GIF89a"
  const uint8_t gif_signature_2[6] = {
      0x47, 0x49, 0x46, 0x38, 0x37, 0x61}; // == "GIF87a"
Francisco Massa's avatar
Francisco Massa committed
31
32

  if (memcmp(jpeg_signature, datap, 3) == 0) {
33
    return decode_jpeg(data, mode, apply_exif_orientation);
Francisco Massa's avatar
Francisco Massa committed
34
  } else if (memcmp(png_signature, datap, 4) == 0) {
35
36
    return decode_png(
        data, mode, /*allow_16_bits=*/false, apply_exif_orientation);
Nicolas Hug's avatar
Nicolas Hug committed
37
38
39
40
  } else if (
      memcmp(gif_signature_1, datap, 6) == 0 ||
      memcmp(gif_signature_2, datap, 6) == 0) {
    return decode_gif(data);
Francisco Massa's avatar
Francisco Massa committed
41
42
43
  } else {
    TORCH_CHECK(
        false,
Nicolas Hug's avatar
Nicolas Hug committed
44
        "Unsupported image file. Only jpeg, png and gif ",
Francisco Massa's avatar
Francisco Massa committed
45
46
47
        "are currently supported.");
  }
}
48
49
50

} // namespace image
} // namespace vision