转为灰度图

cv2.cvtColor(src, code[, dst[, dstCn]])

 

参数:

  • src: 需要转换的图片
  • code: 颜色空间转换码
  • dst: 输出图像大小深度相同, 可选参数
  • desCn: 输出图像的颜色通道, 可选参数
import cv2

cat = cv2.imread("cat.png")
cat = cv2.resize(cat, (640, 554))
# 转换成灰度图
img_gray = cv2.cvtColor(cat, cv2.COLOR_BGR2GRAY)

# 输出维度
print(img_gray.shape) # (554, 640)

# 展示图像
cv2.imshow("img_gray", img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像处理04_可选参数

 

HSV

HSV (Hue, Saturation, Value) 是根据颜色的直观特性由 A.R. Smith 在 1978 年创建的一种颜色空间.

 

# 读取数据
img = cv2.imread("cat.png")
img = cv2.resize(img, (640, 554))
# 转换成hsv
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# 输出维度
print(img_hsv.shape)

# 展示图像
cv2.imshow("img_hsv", img_hsv)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像处理04_可选参数_02

 

 

YUV
YUV 是一种颜色编码的方法, 主要用在视频, 图形处理流水线中.

import cv2
# 读取数据
img = cv2.imread("cat.png")
img = cv2.resize(img, (640, 554))


# 转换成hsv
img_yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)

# 输出维度
print(img_yuv.shape) # (554, 640, 3)

# 展示图像
cv2.imshow("img_yuv", img_yuv)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像处理04_读取数据_03

 

 

二值化操作
格式:

ret, dst = cv2.threshold(src, thresh, maxval, type)
1
参数:

src: 需要转换的图
thresh: 阈值
maxval: 超过阈值所赋的值
type: 二值化操作类型
返回值:

ret: 输入的阈值
dst: 处理好的图片

 

Binary
大于阈值的设为 255, 低于或等于阈值的为 0.

例子:

import cv2
# 读取数据
img = cv2.imread("cat.png")
img = cv2.resize(img, (640, 554))

# 二值化
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# 图片展示
cv2.imshow("thresh1", thresh1)
cv2.waitKey(0)
cv2.destroyAllWindows()

图像处理04_可选参数_04