欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

OpenCV | cv2.cvtcolor() 色域转换

程序员文章站 2024-01-20 17:25:28
...

reference:

Python OpenCV | cv2.cvtColor() method

Syntax: cv2.cvtColor(src, code[, dst[, dstCn]])
Parameters:
src: It is the image whose color space is to be changed.
code: It is the color space conversion code.

需要注意输入图像 src 的类型需要为 float32uint8

常用

灰度转BGR

code 参数为 cv2.COLOR_BGR2GRAY

image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

BGR转灰度

image = cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)

Eg. 从彩色转为灰度

# Python program to explain cv2.cvtColor() method 

# importing cv2 
import cv2 

# path 
path = '...'

# Reading an image in default mode 
src = cv2.imread(path) 

# Window name in which image is displayed 
window_name = 'Image'

# Using cv2.cvtColor() method 
# Using cv2.COLOR_BGR2GRAY color space 
# conversion code 
#---------------------------------------------
image = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
#---------------------------------------------

# Displaying the image 
cv2.imshow(window_name, image) 

Errors

reference:

python: OpenCV depth of image unsupported (CV_64F)

>Unsupported depth of input image:
>     'VDepth::contains(depth)'
> where
>     'depth' is 6 (CV_64F).

CV_64F means the numpy array ‘dtype’ is 64bit floating-point opencv only works with ‘float32’ (32-bit floating point) where image range for imshow is 0.0-1.0 or ‘uint8’ (unsigned 8-bit) 0-255

cvtcolor能接受的参数只能为 float32 或者 uint8 ,需要使用 astype 方法将其转化为需要的类型

img.astype(“float32”)