Python | cv2 cvtcolor()方法

时间:2020-02-23 14:42:14  来源:igfitidea点击:

在本教程中,我们将看到如何使用Python Open-CV将图像的颜色从一个颜色空间更改为另一个颜色空间,该CV存在于CV2(计算机视觉)库中。
我们可以使用 cvtColor()的方法 cv2库将图像的颜色从一个颜色空间转换为另一个颜色空间。
要使用CV2库,我们需要使用CV2库使用 import statement

有超过150个阴影 space transformation techniques可在OpenCV访问。
无论如何,我们将仅调查两个最广泛利用的人, BGR GrayBGR HSV.

BGR -> Blue Green Red
HSV -> Hue Saturation Values
Note :
1) For BGR, Blue,Green,Red value range is [0,255]
2) For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255].

现在让我们看看语法和返回值 cv2 cvtColor()该方法首先,我们将继续前进。

语法

cv2.cvtColor(image, code, dst, dstCn)

参数

我们可以将四个参数传递给CVTColor()方法。
在四个参数中,前2(图像和代码)是强制性的;休息(DST和DSTCN)是可选的。

  • 必要的参数是:
  • image:n维数组的源/输入图像。
  • code:颜色空间的转换代码。

可选参数是:

  • dst:输出与源相同大小和深度的图像。
  • dstCn:目标图像中的通道数。如果将参数置为0,则会自动从图像和代码获取通道的数量。

返回值:

它返回隐蔽的颜色空间图像。

The default color format in OpenCV is often referred to as RGB, but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.

cv2 cvtcolor()方法示例

现在让我们看看Python代码:

示例1:将图像从BGR颜色空间转换为灰色彩色空间。

# import computer vision library(cv2) in this code
import cv2
 
# main code
if __name__ == "__main__" :
 
    # mentioning absolute path of the image
    img_path = "C:\Users\user\Desktop\flower.jpg"
 
    # read/load an image
    image = cv2.imread(img_path)
 
    # show the input image on the newly created window
    cv2.imshow('input image',image)
 
    # convert image from BGR color space to GRAY color space
    convert_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY )
 
    # show the output image on the newly created window
    cv2.imshow('output image',convert_image)

示例2:将图像从BGR颜色空间转换为HSV颜色空间。

# import computer vision library(cv2) in this code
import cv2
 
# main code
if __name__ == "__main__" :
 
    # mentioning absolute path of the image
    img_path = "C:\Users\user\Desktop\flower.jpg"
 
    # read/load an image
    image = cv2.imread(img_path)
 
    # show the input image on the newly created window
    cv2.imshow('input image',image)
 
    # convert image from BGR color space to HSV color space
    convert_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
 
    # show the output image on the newly created window
    cv2.imshow('output image',convert_image)