簡體   English   中英

如何操作在opencv-python中使用minAreaRect()繪制的邊界框內的像素

[英]How to manipulate the pixels inside a bounding box drawn using minAreaRect() in opencv - python

我的圖像有很少的綠色條。 但其中一個是特殊的,因為它連接到藍色的形狀。 我想在特殊的綠色條形圖周圍使用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

此答案將查看圖像中的所有綠色條。 它檢查綠色條是否也包含藍色。

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')

暫無
暫無

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

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