cv2.drawContours не отображает правильный цвет

Я пытаюсь определить ширину артерии и сделал очень грубую программу, чтобы убедиться, что drawContours подходит. Моя проблема в том, что контур печатает только черные или белые линии, а не цветные линии, которые я пытаюсь использовать. Я не уверен, что img, на котором я рисую, ограничено черно-белым изображением или у меня неправильно настроен контур. Второе изображение — это контуры, добавленные к исходному изображению. Выведенные изображения

import cv2
import numpy
from FileSupport import *

# Declared Variables ###########################
# file vars
image_file_name = '14.05.25 hrs __[0011697].avi'  # this will be given through some file selection of the user
temp_image_file_path = ReturnTempImagePath()  # gives file path for .avi files to be stored
# image vars
sample_start_row = 144  # measurements are based off the 640x480 sample image
sample_end_row = 408
sample_start_col = 159
sample_end_col = 518
# colors
RED = (0, 0, 255)  # opencv uses BGR not RGB
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)

# Pull image ###################################
print("Getting image from ", image_file_name, "\n")

artery_vid = cv2.VideoCapture(ReturnImagePath(image_file_name))
if not artery_vid.isOpened():
    print("Couldn't open file")
    sys.exit()

success, image = artery_vid.read()
i_frame = 0
while success:
    image = image[sample_start_row:sample_end_row, sample_start_col:sample_end_col]
    cv2.imwrite(temp_image_file_path + "frame%i.jpg" % i_frame, image)

    # -----Just trying to draw around artery-------
    img = cv2.imread(temp_image_file_path + "frame%i.jpg" % i_frame, cv2.IMREAD_GRAYSCALE)
    hierarchy, threshold = cv2.threshold(img, 120, 200, cv2.THRESH_BINARY)
    contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    cv2.imshow("Image Without Contours", image)  # contour is also destructive
    cv2.drawContours(img, contours, -1, GREEN, 2)  # I am expecting the contour lines to be green
    cv2.imshow("Image With Contours", img)
    cv2.imshow("Threshold Image", threshold)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    # ---------------------------------------------

    print("Image %i Complete" % i_frame, "\n")
    i_frame += 1
    success, image = artery_vid.read()

person Daniel me    schedule 20.11.2019    source источник


Ответы (1)


Ваше изображение в оттенках серого, поэтому вам необходимо преобразовать его в BGR, прежде чем рисовать контуры в цвете.

contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow("Image Without Contours", image)  # contour is also destructive

img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)  #add this line

cv2.drawContours(img, contours, -1, GREEN, 2)  # I am expecting the contour lines to be green
person Piotr Siekański    schedule 20.11.2019
comment
Это было прекрасно - person Daniel me; 20.11.2019