我正在使用python在opencv中基于图像处理开发我的项目。
我有一个带有蓝色矩形边框的页面,其内部由相机捕获。我需要检测边界以提取边界内的内容以供进一步处理。我尝试过轮廓,边界Rect以及Hough圆形绘制矩形角落有4个圆圈。
我使用hsv转换来检测蓝色。
我未能准确地获得边界。这是我的代码。 `
import cv2
import numpy as np
def nothing(x):
pass
img=np.zeros((640,480,3),np.uint8)
cv2.namedWindow('image',cv2.WINDOW_AUTOSIZE)
cv2.createTrackbar('kernel','image',1,10,nothing)
cv2.createTrackbar('iteration','image',1,10,nothing)
cap = cv2.VideoCapture(0)
while(1):
ret, frame = cap.read()
frame=cv2.GaussianBlur(frame,(5,5),0)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
ker = cv2.getTrackbarPos('kernel','image')
its = cv2.getTrackbarPos('iteration','image')
lower_array=np.array([75,100,100])
upper_array=np.array([110,255,255])
### Threshold the HSV image to get only blue colors
mask = cv2.inRange(hsv, lower_array, upper_array)
edges = cv2.Canny(mask,90,200)
## Image Processing to obtain better image
kernel = np.ones((ker,ker),np.uint8)
erosion = cv2.erode(edges,kernel,iterations = its)
dilation = cv2.dilate(erosion,kernel,iterations = its)
opening = cv2.morphologyEx(dilation, cv2.MORPH_OPEN, kernel)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel)
## ret,thresh = cv2.threshold(closing,127,255,0)
image, contours, hierarchy = cv2.findContours(closing,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours_poly=[]
bounding_rect=[]
hull=[]
res = cv2.bitwise_and(frame,frame, mask= closing)
## Find the largest contour
max_area = 0
if(contours):
for cnt in contours:
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
best_cnt = cnt
## Finding centroids of best_cnt and draw a circle there
M = cv2.moments(best_cnt)
cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])
cv2.circle(frame,(cx,cy),5,(0,255,0),-1)
##To approximate the contour
epsilon = 0.01*cv2.arcLength(best_cnt,True)
approx = cv2.approxPolyDP(best_cnt,epsilon,True)
## Draw the largest contour
cv2.drawContours(res, [best_cnt], 0, (0,255,0), 3)
#x,y,w,h = cv2.boundingRect(best_cnt)
#cv2.rectangle(res,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imshow('image1',frame)
cv2.imshow('image2',mask)
cv2.imshow('image3',dilation)
cv2.imshow('image6',edges)
cv2.imshow('image4',closing)
cv2.imshow('image5',res)
if cv2.waitKey(1) & 0xFF==ord('q'):
break
cap.release()
cv2.destroyAllWindows()
`