[opencv-python]学习-图像处理

图像处理

150多种颜色空间中,我们常用的有BGR,Gray和HSV。
BGR <–> Gray and BGR <–> HSV.

opencv 里使用cv2.cvtColor(input_image, flag) 来进行转换, flag 表示转换类型。

  • cv2.COLOR_BGR2GRAY. BGR <–> Gray
  • cv2.COLOR_BGR2HSV. BGR <–> HSV

查看所有类型:

flags = [i for i in dir(cv2) if i.startswith('COLOR_')]
print(flags)

For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255]. Different softwares use different scales. So if you are comparing OpenCV values with them, you need to normalize these ranges.

[opencv-python]学习-图像处理_第1张图片
By SharkDderivative work: SharkD [CC BY-SA 3.0 or GFDL], via Wikimedia Commons

透明图

RGB图转换为RGBA,更改alpha通道值(0表示完全透明,255表示完全不透明)

# First create the image with alpha channel
rgba = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2RGBA)

# Then assign the mask to the last channel of the image
rgba[:, :, 3] = alpha_data

or

b_channel, g_channel, r_channel = cv2.split(img)

alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 50 #creating a dummy alpha channel image.

img_BGRA = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))

目标提取

img = cv2.imread('../img/opencv.png')

# Convert BGR to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# define range of blue color in HSV
lower_blue = np.array([110, 50, 50])
upper_blue = np.array([130, 255, 255])

# Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_blue, upper_blue)

# Bitwise-AND mask and original image
res = cv2.bitwise_and(img, img, mask=mask)
cv2.imwrite('../res/opencv_hsv.png', res)

原图
[opencv-python]学习-图像处理_第2张图片

结果
[opencv-python]学习-图像处理_第3张图片

如何知道颜色的hsv值呢

参考如下方法

green = np.uint8([[[0,255,0 ]]])
hsv_green = cv2.cvtColor(green,cv2.COLOR_BGR2HSV)
# [[[ 60 255 255]]]
print(hsv_green)

Thresholding Operations using inRange: https://docs.opencv.org/3.4.15/da/d97/tutorial_threshold_inRange.html

https://gitee.com/carlzhangweiwen/python-opencv-learn
https://opencv24-python-tutorials.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html#converting-colorspaces

opencv 用到的图片都在这里:https://github.com/opencv/opencv/tree/master/samples/data

python OpenCV - add alpha channel to RGB image https://stackoverflow.com/questions/32290096/python-opencv-add-alpha-channel-to-rgb-image

你可能感兴趣的:(python,opencv,python,图像处理)