如何在 OpenCV(Python)中将灰度图像转换为 RGB?

How does one convert a grayscale image to RGB in OpenCV (Python)?(如何在 OpenCV(Python)中将灰度图像转换为 RGB?)
本文介绍了如何在 OpenCV(Python)中将灰度图像转换为 RGB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在学习使用 OpenCV 进行实时应用程序的图像处理.我对图像进行了一些阈值处理,并希望将轮廓标记为绿色,但它们没有以绿色显示,因为我的图像是黑白的.

I'm learning image processing using OpenCV for a realtime application. I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.

在程序的早期,我使用 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 将 RGB 转换为灰度,但返回时我很困惑,函数 backtorgb = cv2.cvtColor(gray,cv2.CV_GRAY2RGB) 给:

Early in the program I used gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) to convert from RGB to grayscale, but to go back I'm confused, and the function backtorgb = cv2.cvtColor(gray,cv2.CV_GRAY2RGB) is giving:

AttributeError: 'module' 对象没有属性 'CV_GRAY2RGB'.

下面的代码似乎没有以绿色绘制轮廓.这是因为它是灰度图像吗?如果是这样,我可以将灰度图像转换回 RGB 以显示绿色的轮廓吗?

The code below does not appear to be drawing contours in green. Is this because it's a grayscale image? If so, can I convert the grayscale image back to RGB to visualize the contours in green?

import numpy as np
import cv2
import time

cap = cv2.VideoCapture(0)
while(cap.isOpened()):

    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    ret, gb = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)

    gb = cv2.bitwise_not(gb)

    contour,hier = cv2.findContours(gb,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)

    for cnt in contour:
        cv2.drawContours(gb,[cnt],0,255,-1)
    gray = cv2.bitwise_not(gb)

    cv2.drawContours(gray,contour,-1,(0,255,0),3)

    cv2.imshow('test', gray)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

推荐答案

我将我的评论推广到一个答案:

I am promoting my comment to an answer:

简单的方法是:

您可以在原始框架"本身中绘制,而不是使用灰色图像.

You could draw in the original 'frame' itself instead of using gray image.

艰难的方式(您尝试实施的方法):

The hard way (method you were trying to implement):

backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) 是正确的语法.

这篇关于如何在 OpenCV(Python)中将灰度图像转换为 RGB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reading *.mhd/*.raw format in python(在 python 中读取 *.mhd/*.raw 格式)
Count number of cells in the image(计算图像中的单元格数)
How to detect paragraphs in a text document image for a non-consistent text structure in Python OpenCV(如何在 Python OpenCV 中检测文本文档图像中的段落是否存在不一致的文本结构)
How to get the coordinates of the bounding box in YOLO object detection?(YOLO物体检测中如何获取边界框的坐标?)
Divide an image into 5x5 blocks in python and compute histogram for each block(在 python 中将图像划分为 5x5 块并计算每个块的直方图)
Extract cow number from image(从图像中提取奶牛编号)