OpenCV canny边缘检测不绘制边界框

问题描述 投票:0回答:1

我有一个图像,我想做边缘检测并为其绘制边界框,我的问题是我的Python代码没有绘制边界框,我不确定它是否是这样,因为它无法检测到其中的任何对象它或者我只是画错了矩形。

在此输入图片描述

这是我的尝试

import cv2
import numpy as np

img = cv2.imread("image1.jpg")
(B, G, R) = cv2.split(img)
img = cv2.Canny(B, 20, 100)   # Blue channel gives the best box so far
# img = cv2.Canny(R, 20, 100)
# img = cv2.Canny(R, 20, 100)


ret,thresh = cv2.threshold(img,20,100,0)
contours,hierarchy = cv2.findContours(thresh, 1, 2)


cnt = contours[0]
M = cv2.moments(cnt)

for c in contours:
    rect = cv2.minAreaRect(c)
    box = cv2.boxPoints(rect)
    box = np.intp(box)
    img = cv2.drawContours(img,[box],0,(0,0,255),2)



# display the image with bounding rectangle drawn on it 
# cv2.namedWindow('Bounding Rectangle', cv2.WINDOW_KEEPRATIO)
cv2.imshow('Bounding Rectangle', img) 

cv2.waitKey(0) 
cv2.destroyAllWindows() 

这会产生这个图像

在此输入图片描述

我期待这样的图像:

在此输入图片描述

python opencv edge-detection
1个回答
0
投票

尝试:

import cv2
import numpy as np
# Load the image
cimg = cv2.imread('bBox.jpg')
# Convert to grayscale
img = cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY)
# Apply threshold or other color segmentation
_, img = cv2.threshold(img, 95, 255, cv2.THRESH_BINARY)
# Find contours
contours , _ = cv2.findContours(img, 1, 2)
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#exit()
count=0
for cnt in contours :
    count+=1
    print(f"{count}, {cnt=}")
    # Fit a minimum area rectangle
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.intp(box)
    # Draw the bounding box
    cv2.drawContours(cimg, [box], 0, (0, 255, 0), 5)

# Show the image
cv2.imshow('Rotated Bounding Box', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

originalImage

bBoxes

© www.soinside.com 2019 - 2024. All rights reserved.