img_buffer_convert.md 1.7 KB
Newer Older
F
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
# 甲壳虫的Base64之旅

如下的一只甲壳虫,我们希望把它编码成 Base64,再从Base64解码出来。
![](./bug.jpg)

代码框架如下:

```python
import numpy as np
import cv2
import base64

def img_to_base64(img):
    # TODO(You):

def img_from_base64(img_base64):
    # TODO(You):

if __name__ == '__main__':
    img = cv2.imread('bug.jpg')

    img_base64 = img_to_base64(img)
    img = img_from_base64(img_base64)

    cv2.imshow('img_decode', img)
    cv2.waitKey()
    cv2.destroyAllWindows()
```

以下对两个函数实现正确的是?

## 答案

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    img = cv2.imdecode(jpg_as_np, flags=1)
    return img
```

## 选项

### A

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)[1])

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    img = cv2.imdecode(jpg_original, flags=1)
    return img
```

### B

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)).decode()

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
    img = cv2.imdecode(jpg_as_np, flags=1)
    return img
```

### C

```python
def img_to_base64(img):
    return base64.b64encode(cv2.imencode('.jpg', img)[1]).decode()

def img_from_base64(img_base64):
    jpg_original = base64.b64decode(img_base64)
    jpg_as_np = np.frombuffer(jpg_original)
    img = cv2.imdecode(jpg_as_np, flags=1)
    return img
```