How does one convert a grayscale image to RGB in OpenCV (Python) for visualizing contours after processing an image in binary?

匿名 (未验证) 提交于 2019-12-03 01:59:02

问题:

I am 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.

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

The code below does not appear to be drawing contours in green - is this because it's a greyscale 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() 

回答1:

I am promoting my comment to an answer:

The easy way is:

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) is the correct syntax.



回答2:

Try this:

import cv2 import cv  color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB) 

I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.



回答3:

One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:

CvtColor(input, output, CV_GRAY2BGR) 

OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!