在C++中垂直翻转图像,不使用外部库如OpenCV。

huangapple go评论49阅读模式
英文:

Flip image vertically in C++ without external libraries like OpenCV

问题

我有以下的函数,它接收void*类型的图像数据。如何在不使用像OpenCV这样的外部库的情况下将其上下翻转?已知图像的宽度和高度。

注意:这个函数将在Android上以每秒至少30次的频率调用,所以需要高效的解决方案。

PushVideoFrame(void *bytes, int width, int height) {
    if (clientPtr == nullptr) {
        return ErrorCodes::DEVICE_CONNECTION;
    }

    char* data = static_cast<char*>(bytes);

    //////// 翻转图像的代码 /////////////

    clientPtr->PushVideoFrameAsync(data, width * height * 4);
}
英文:

I have the following function which receives image as void*. How can I flip it upside down without using external libraries like OpenCV. Image width and height are known.

Note: this function will be called at least 30 times a second on Android so this needs to be efficient.

PushVideoFrame(void *bytes, int width, int height) {
    if (clientPtr == nullptr) {
        return ErrorCodes::DEVICE_CONNECTION;
    }

     char* data = static_cast&lt; char *&gt;(bytes);

     //////// CODE TO FLIP IMAGE /////////////

    clientPtr-&gt;PushVideoFrameAsync(data, width * height * 4)
}

答案1

得分: 0

你可以使用额外内存来交换行:

void flipVertically(uint8_t *data, int width, int height) {
    vector<uint8_t> temp(width);
    for (int i = 0; i < height / 2; i++) {
        void *ptr1 = data + i * width;
        void *ptr2 = data + (height - i - 1) * width;
        
        // 使用临时缓冲区交换(行1,行2)
        memcpy(&temp[0], ptr1, width);
        memcpy(ptr1, ptr2, width);
        memcpy(ptr2, &temp[0], width);
    }
}

这段代码用于垂直翻转图像数据的行。

英文:

You can swap rows with additional memory:

void flipVertically(uint8_t *data, int width, int height) {
    vector&lt;uint8_t&gt; temp(width);
    for (int i = 0; i &lt; height / 2; i++) {
        void *ptr1 = data + i*width;
        void *ptr2 = data + (height-i-1)*width;
        
        // swap(row1, row2) with temp buffer
        memcpy(&amp;temp[0], ptr1, width);
        memcpy(ptr1, ptr2, width);
        memcpy(ptr2, &amp;temp[0], width);
    }
}

huangapple
  • 本文由 发表于 2023年2月8日 23:57:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定