如何使用ROI从所需的点绘制矩形?

时间:2018-09-14 16:20:17

标签: numpy opencv roi

您好,我是OpenCv的初学者。 我有一个迷宫的图像。我写了迷宫求解器代码。我需要像图片一样获取照片,此代码才能正常工作。 我想使用ROI选择白色区域的轮廓,但是我不能

当我尝试ROI方法时,我得到一个带有黑色区域的平滑矩形。

https://i.stack.imgur.com/Ty5BX.png ----->这是我的代码结果

https://i.stack.imgur.com/S7zuJ.png -------->我想要这个结果

import cv2
import numpy as np

#import image
image = cv2.imread('rt4.png')

#grayscaleqq
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#cv2.imshow('gray', gray)
#qcv2.waitKey(0)

#binary
#ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
threshold = 150
thresh = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)[1]
cv2.namedWindow('second', cv2.WINDOW_NORMAL)
cv2.imshow('second', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()

#dilation
kernel = np.ones((1,1), np.uint8)
img_dilation = cv2.dilate(thresh, kernel, iterations=1)
cv2.namedWindow('dilated', cv2.WINDOW_NORMAL)
cv2.imshow('dilated', img_dilation)
cv2.waitKey(0)
cv2.destroyAllWindows()




#find contours
im2,ctrs, hier = cv2.findContours(img_dilation.copy(), 
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)


#sort contours
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr) 
[0])

list = []

for i, ctr in enumerate(sorted_ctrs):
# Get bounding box
x, y, w, h = cv2.boundingRect(ctr)

# Getting ROI
roi = image[y:y+h, x:x+w]

a = w-x
b = h-y
list.append((a,b,x,y,w,h))


# show ROI
#cv2.imshow('segment no:'+str(i),roi)
cv2.rectangle(image,(x,y),( x + w, y + h ),(0,255,0),2)
#cv2.waitKey(0)

if w > 15 and h > 15:
    cv2.imwrite('home/Desktop/output/{}.png'.format(i), roi)

cv2.namedWindow('marked areas', cv2.WINDOW_NORMAL)
cv2.imshow('marked areas',image)
cv2.waitKey(0)
cv2.destroyAllWindows()




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

gray = np.float32(gray)
dst = cv2.cornerHarris(gray,2,3,0.04)

#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)


image[dst>0.01*dst.max()]=[0,0,255]

cv2.imshow('dst',image)
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()

list.sort()
print(list[len(list)-1])

1 个答案:

答案 0 :(得分:0)

仅绘制倾斜矩形的简单解决方案是使用cv2.polylines。根据您的结果,我假设您已经具有该区域的顶点的坐标,将其称为[x1,y1],[x2,y2],[x3,y3],[x4,y4]。折线功能会在顶点之间绘制一条线,以创建一个封闭的多边形。

import cv2
import numpy as np

#List coordinates of vertices as an array
pts = np.array([[x1,y1],[x2,y2],[x3,y3],[x4,y4]], np.int32)
pts = pts.reshape((-1,1,2))

#Draw lines from vertex to vertex
cv2.polylines(image, [pts], True, (255,0,0))