MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / preprocess_image

Function preprocess_image

lite/example/cpp_example/mge/cv/detect_yolox.cpp:29–78  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

27namespace {
28
29void preprocess_image(
30 uint8_t* image, const int width, const int height, const int channel,
31 std::shared_ptr<Tensor> tensor) {
32 auto layout = tensor->get_layout();
33 for (size_t i = 0; i < layout.ndim; i++) {
34 printf("model input shape[%zu]=%zu \n", i, layout.shapes[i]);
35 }
36
37 //! resize to target shape
38 float r = std::min(INPUT_W / (width * 1.0), INPUT_H / (height * 1.0));
39 int unpad_w = r * width;
40 int unpad_h = r * height;
41
42 std::shared_ptr<std::vector<uint8_t>> resize_int8 =
43 std::make_shared<std::vector<uint8_t>>(unpad_w * unpad_h * channel);
44 stbir_resize_uint8(
45 image, width, height, 0, resize_int8->data(), unpad_w, unpad_h, 0, channel);
46
47 std::shared_ptr<std::vector<uint8_t>> padded;
48 if (unpad_h != INPUT_H || unpad_w != INPUT_W) {
49 padded = std::make_shared<std::vector<uint8_t>>(
50 INPUT_H * INPUT_W * channel, 114);
51 for (int h = 0; h < unpad_h; h++) {
52 for (int w = 0; w < unpad_w; w++) {
53 for (int c = 0; c < channel; c++) {
54 (*padded)[h * INPUT_W * channel + w * channel + c] =
55 (*resize_int8)[h * unpad_w * channel + w * channel + c];
56 }
57 }
58 }
59 } else {
60 padded = resize_int8;
61 }
62
63 tensor->set_layout({{1, 3, 640, 640}, 4});
64
65 std::vector<float> mean = {0.485, 0.456, 0.406};
66 std::vector<float> std = {0.229, 0.224, 0.225};
67
68 //! convert form rgb to bgr, relayout from hwc to chw, normalization copy to tensor
69 float* in_data = static_cast<float*>(tensor->get_memory_ptr());
70 size_t pixels = INPUT_H * INPUT_W;
71 for (size_t i = 0; i < pixels; i++) {
72 in_data[i] = (padded->at(i * channel + 0) / 255.0f - mean[0]) / std[0];
73 in_data[i + 1 * pixels] =
74 (padded->at(i * channel + 1) / 255.0f - mean[1]) / std[1];
75 in_data[i + 2 * pixels] =
76 (padded->at(i * channel + 2) / 255.0f - mean[2]) / std[2];
77 }
78}
79
80struct Rect {
81 float x;

Callers 1

detect_yoloxFunction · 0.70

Calls 7

stbir_resize_uint8Function · 0.85
minFunction · 0.50
get_layoutMethod · 0.45
dataMethod · 0.45
set_layoutMethod · 0.45
get_memory_ptrMethod · 0.45
atMethod · 0.45

Tested by

no test coverage detected