問題描述
我正在學習使用 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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!