OpenCV | cv2.cvtcolor() 色域转换

本文介绍了OpenCV中用于色域转换的方法cv2.cvtColor(),详细解析了如何进行灰度转BGR和BGR转灰度操作。同时,文章提醒在使用该函数时需要注意输入图像的数据类型必须为float32或uint8,并提供了解决不支持数据类型问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值