簡體   English   中英

如何使用opencv python在兩個變量中獲取圖像中兩條單獨行的RGB值

[英]How to get RGB values of two separate lines in an image in two variables using opencv python

我使用 cv2 檢測到圖像中的兩條線。 現在我想在單獨的變量中獲取兩條線的 RGB 值,例如 left_line_veriable = ['rgb values'], right_line_rgb_values = ['rgb values']

這是我的代碼:

import cv2
import numpy as np

image = cv2.imread('tape.png')
image = cv2.cvtCOLOR(image, cv2.COLOR_BGR2GRAY)

# Apply adaptive threshold
image_thr = cv2.adaptiveThreshold(image, 255, cv2.THRESH_BINARY_INV, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, 81, 2)

# Apply morphological opening with vertical line kernel
kernel = np.ones((image.shape[0], 1), dtype=np.uint8) * 255
image_mop = cv2.morphologyEx(image_thr, cv2.MORPH_OPEN, kernel)

color_detected_img = cv2.bitwise_and(image, image, mask=image_mop)

cv2.imshow('image', color_detected_img)

cv2.waitKey(0)
cv2.destroyAllWindows()

這是我想從中獲取兩個變量中的兩條線的 RGB 值的圖像,如上所述:

在此處輸入圖像描述

也許不是最優的方式,但並不難做到。 正如我在評論中所說,您可以標記圖像以分割線條,然后獲取其中 rgb 值的平均值和平均位置以了解哪個是左邊和右邊。 這是一個小腳本來演示我在說什么。 最后一部分只是為了展示結果。

import cv2
import numpy as np

# load img and get the greyscale
img = cv2.imread("x.png")
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# label the image
ret, thres = cv2.threshold(grey, 1, 255, cv2.THRESH_BINARY)
labelAmount, labels = cv2.connectedComponents(thres)

# get the mean of the color and position
values = []
# first label (0) is background
for i in range(1, labelAmount):
  mask = np.zeros(labels.shape, dtype=np.uint8)
  mask[labels == i] = 255
  mean = cv2.mean(img, mask)[:-1]
  meanPos = np.mean(cv2.findNonZero(mask), axis=0)[0]
  values.append((mean, meanPos))

# sort them by x value (left to right)
values = sorted(values, key = lambda v : v[1][0])

left_line_color = values[0][0]
right_line_color = values[1][0]

# just to show the results
left_only = np.zeros(img.shape, dtype=np.uint8)
right_only = np.zeros(img.shape, dtype=np.uint8)
left_only = cv2.line (left_only, (int(values[0][1][0]), 0), (int(values[0][1][0]), img.shape[0]), left_line_color,5 )
right_only = cv2.line (right_only, (int(values[1][1][0]), 0), (int(values[1][1][0]), img.shape[0]), right_line_color,5 )
cv2.imshow("left_line", left_only)
cv2.imshow("right_line", right_only)
cv2.imshow("original", img)
cv2.waitKey(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM