Advertisement

python opencv 识别圆角矩形,OpenCV-如何找到圆角矩形的矩形轮廓?

阅读量:

I am attempting to detect the contour of a rectangular object with rounded corners within a picture. I utilized HoughLinesP and findContours, yet was unsuccessful in achieving my goal.

65de33bf0f33e170345b1dcc0cc22b6b.png

I want to find the rectangle like this:

28d41279e1d75d8190c545278b66a48a.png

Code:

import cv2

import matplotlib.pyplot as plt

import util

image = cv2.imread("./img/findrect0.png", 1)

gray = util.grayImage(image)

edges = cv2.Canny(image, 50, 200)

lines = cv2.HoughLinesP(edges, 1, cv2.cv.CV_PI/180, 50, minLineLength=50, maxLineGap=10)[0]

linesImage = image.copy()

util.drawLines(linesImage, lines, thickness=10)

contoursImage = image.copy()

(contours, hierarchy) = cv2.extract contours(gray.copy(), external contour retrieval method, simplified approximation of the contours)

util.drawContours(contoursImage, contours, thickness=10)

util.showOpenCVImagesGrid([image, edges, linesImage, contoursImage], 2, 2, titles=["original image", "canny image", "lines image", "contours image"])

util:

import cv2

import math

import matplotlib.pyplot as plt

def showOpenCVImagesGrid(images, x, y, titles=None, axis="on"):

fig = plt.figure()

i = 1

for image in images:

copy = image.copy()

channel = len(copy.shape)

cmap = None

if channel == 2:

cmap = "gray"

elif channel == 3:

copy = cv2.cvtColor(copy, cv2.COLOR_BGR2RGB)

elif channel == 4:

copy = cv2.cvtColor(copy, cv2.COLOR_BGRA2RGBA)

fig.add_subplot(x, y, i)

if titles is not None:

plt.title(titles[i-1])

plt.axis(axis)

plt.imshow(copy, cmap=cmap)

i += 1

plt.show()

def grayImage(image):

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

return gray

def drawLines(image, lines, thickness=1):

for line in lines:

print("line="+str(line))

cv2.line(image, (line[0], line[1]), (line[2], line[3]),

(0, 0, 255), thickness)

def drawContours(image, contours, thickness=1):

i = 0

for contour in contours:

cv2.drawContours(image, [contours[i]], i, (0, 255, 0), thickness)

area = cv2.contourArea(contour)

i += 1

I'm using Python 2.7.13 and OpenCV 2.4.13.3.

I am planning to continue these lines in order to identify their intersection points. Ultimately, I will obtain four coordinates of the rectangle.

But if the image is more complex, I don't know how to deal with.

解决方案

You need to find the bounding rectangle of the found contours.

img = cv2.imread("image.png", -1)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

binary = cv2.bitwise_not(gray)

(,contours,) = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for contour in contours:

(x,y,w,h) = cv2.boundingRect(contour)

cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)

d4ff05ce3a53f6d1d103222d7a5070df.png

全部评论 (0)

还没有任何评论哟~