繁体   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