【问题标题】:How to manipulate the pixels inside a bounding box drawn using minAreaRect() in opencv - python如何在opencv中操作使用minAreaRect()绘制的边界框内的像素 - python
【发布时间】:2019-06-03 13:04:35
【问题描述】:

我有一个带有几个绿色条的图像。但其中一个很特别,因为它与蓝色形状相连。我想在特殊的绿色条周围使用 minAreaRect() 绘制一个边界框。

到目前为止,我能够在所有绿色条周围使用 minAreaRect() 绘制边界框。但是为了过滤绿色条并只取特殊的条,我需要确定哪个框包含蓝色像素。

为了做到这一点,我想检查每个框内的每个像素,以检查哪个包含蓝色像素。有什么方法可以识别边界框内像素的像素坐标。还是有更好的方法?

import cv2 as cv
import numpy as np

# Load the aerial image and convert to HSV colourspace
image = cv.imread("1.png")
image1 = image
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)

# Define lower and uppper limits of the color blue
low_blue = np.array([94, 80, 2])
high_blue = np.array([126, 255, 255])

# Mask image to only select blues
mask1 = cv.inRange(hsv, low_blue, high_blue)

# Change image to green where we found blue
image[mask1 > 0] = (0, 130, 0)


blurred_frame = cv.GaussianBlur(image, (5, 5), 0)
hsv = cv.cvtColor(blurred_frame, cv.COLOR_BGR2HSV)
low_green = np.array([25, 52, 72])
high_green = np.array([102, 255, 255])
mask = cv.inRange(hsv, low_green, high_green)
_, contours, _ = cv.findContours(mask, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
image[mask1 > 0] = (255, 0, 0)

for contour in contours:

    rect = cv.minAreaRect(contour)
    box = cv.boxPoints(rect)
    box = np.int0(box)
    Cx = rect[0][0]
    Cy = rect[0][1]

    cv.drawContours(image, [box], 0, (0, 0, 255), 2)

cv.imshow("Frame", image)
cv.waitKey(0)
cv.destroyAllWindows()

这是输入图像

https://ibb.co/h9cv4DN

这是预期的输出(用紫色表示的边界框)

https://ibb.co/8Mq6Mwt

【问题讨论】:

  • 你能发布在所有绿色条周围绘制矩形的代码吗?
  • @StephenMeschke 我已经用我尝试过的代码更新了这个问题。请检查。谢谢。

标签: python opencv image-processing contour opencv-contour


【解决方案1】:

此答案查看图像中的所有绿色条。它检查绿色条是否也包含蓝色。

for contour in contours:

    rect = cv.minAreaRect(contour)
    box = cv.boxPoints(rect)
    box = np.int0(box)
    Cx = rect[0][0]
    Cy = rect[0][1]

    # Make a mask of this single green line
    mask = np.zeros_like(mask1)
    cv.drawContours(mask, [contour], 0, 255, cv.FILLED)
    sigle_green_line = cv.bitwise_and(image, image, mask = mask)
    sigle_green_line = cv.cvtColor(sigle_green_line, cv.COLOR_BGR2HSV)
    # Check how much blue is in the image
    blue_mask = cv.inRange(sigle_green_line, low_blue, high_blue)
    print(sum(sum(blue_mask)))
    # If the image is not all black (all zeros) the contour contains some blue
    if sum(sum(blue_mask)) > 0: print('This contour contains some blue')

【讨论】:

  • 非常感谢您的解决方案。我以前能够通过获取每个矩形的中心像素并比较它们的颜色来检查哪个包含蓝色来解决这个问题。该逻辑适用于我的场景,因为在我的情况下,如果存在蓝色,它始终位于绿色条的中间。但是您的逻辑是完美的解决方案,也可以应用于其他场景。你拯救了这一天。
猜你喜欢
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2021-09-27
  • 2013-01-08
  • 2016-01-18
  • 1970-01-01
相关资源
最近更新 更多