# 提取花瓣

OpenCV 的颜色空间主要有 BGR、HSV、Lab等，`cvtColor` 函数可以让图像在不同颜色空间转换。例如通过将花的图像转换到 HSV 颜色空间，在HSV空间内过滤出只含有花瓣颜色的像素，从而提取出花瓣。

![](./flower_only.jpeg)

以下实现正确的是？

## 答案

```python
import numpy as np
import cv2

if __name__ == '__main__':
    flower = cv2.imread('flower.jpeg', -1)
    hsv = cv2.cvtColor(flower, cv2.COLOR_BGR2HSV)

    lower_red = np.array([0, 20, 100])
    upper_red = np.array([10, 255, 255])

    mask = cv2.inRange(hsv, lower_red, upper_red)
    res = cv2.bitwise_and(flower, flower, mask=mask)

    images = np.concatenate((flower, res), axis=1)
    cv2.imshow('flower', images)
    cv2.waitKey()
    cv2.destroyAllWindows()
```

## 选项

### 颜色空间转换错误

```python
import numpy as np
import cv2

if __name__ == '__main__':
    flower = cv2.imread('flower.jpeg', -1)
    hsv = cv2.cvtColor(flower, cv2.COLOR_BGR2GRAY)

    lower_red = np.array([0, 20, 100])
    upper_red = np.array([10, 255, 255])

    mask = cv2.inRange(hsv, lower_red, upper_red)
    res = cv2.bitwise_and(flower, flower, mask=mask)

    images = np.concatenate((flower, res), axis=1)
    cv2.imshow('flower', images)
    cv2.waitKey()
    cv2.destroyAllWindows()
```

### 色调上下限错误

```python
import numpy as np
import cv2

if __name__ == '__main__':
    flower = cv2.imread('flower.jpeg', -1)
    hsv = cv2.cvtColor(flower, cv2.COLOR_BGR2GRAY)

    lower_red = np.array([0, 0, 0])
    upper_red = np.array([0, 0, 255])

    mask = cv2.inRange(hsv, lower_red, upper_red)
    res = cv2.bitwise_and(flower, flower, mask=mask)

    images = np.concatenate((flower, res), axis=1)
    cv2.imshow('flower', images)
    cv2.waitKey()
    cv2.destroyAllWindows()
```

### 颜色空间转换错误2

```python
import numpy as np
import cv2

if __name__ == '__main__':
    flower = cv2.imread('flower.jpeg', -1)
    hsv = cv2.cvtColor(flower, cv2.COLOR_RGB2HSV)

    lower_red = np.array([0, 20, 100])
    upper_red = np.array([10, 255, 255])

    mask = cv2.inRange(hsv, lower_red, upper_red)
    res = cv2.bitwise_and(flower, flower, mask=mask)

    images = np.concatenate((flower, res), axis=1)
    cv2.imshow('flower', images)
    cv2.waitKey()
    cv2.destroyAllWindows()
```
