def findContours(arg_img,arg_canvas, arg_MinMaxArea=False, arg_debug= False):
image= arg_img.copy()
#print image
canvas= arg_canvas.copy()
if len(image)==3:
image = cv2.cvtColor(self.image, cv2.COLOR_GRAY2BGR)
if sys.version_info.major == 2:
ctrs, hier = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
else:
_, ctrs, hier = cv2.findContours(image.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if arg_MinMaxArea is not False:
ctrs = filter(lambda x : arg_MinMaxArea[1]> cv2.contourArea(x) > arg_MinMaxArea[0] , ctrs)
print '>>> ', len(ctrs)
for ctr in ctrs:
print 'Area: ', cv2.contourArea(ctr)
cv2.drawContours(canvas, [ctr], 0, (0, 128, 255), 3)
if arg_debug:
cv2.imwrite('Debug/debug_findContours.jpg',canvas)
return canvas
python类drawContours()的实例源码
def get_contour(self, arg_frame, arg_export_index, arg_export_path, arg_export_filename, arg_binaryMethod):
# Otsu's thresholding after Gaussian filtering
tmp = cv2.cvtColor(arg_frame, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(tmp,(5,5),0)
if arg_binaryMethod== 0:
ret, thresholdedImg= cv2.threshold(blur.copy() , self.threshold_graylevel, 255 , 0)
elif arg_binaryMethod == 1:
ret,thresholdedImg = cv2.threshold(blur.copy(),0 ,255 ,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
elif arg_binaryMethod== 2:
thresholdedImg = cv2.adaptiveThreshold(blur.copy(),255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,0)
result = cv2.cvtColor(thresholdedImg, cv2.COLOR_GRAY2RGB)
ctrs, hier = cv2.findContours(thresholdedImg, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
ctrs = filter(lambda x : cv2.contourArea(x) > self.threshold_size , ctrs)
rects = [[cv2.boundingRect(ctr) , ctr] for ctr in ctrs]
for rect , cntr in rects:
cv2.drawContours(result, [cntr], 0, (0, 128, 255), 3)
if arg_export_index:
cv2.imwrite(arg_export_path+ arg_export_filename+'.jpg', result)
print "Get Contour success"
return result
def draw_silhouette(self, foreground, bin_mask, tracked_object_stats, centroid):
contours = cv2.findContours(bin_mask, mode=cv2.RETR_LIST, method=cv2.CHAIN_APPROX_SIMPLE)[1]
for i_contour in range(0, len(contours)):
cv2.drawContours(foreground, contours, i_contour, (0, 255, 0))
x1 = tracked_object_stats[cv2.CC_STAT_LEFT]
x2 = x1 + tracked_object_stats[cv2.CC_STAT_WIDTH]+1
y1 = tracked_object_stats[cv2.CC_STAT_TOP]
y2 = y1 + tracked_object_stats[cv2.CC_STAT_HEIGHT]+1
if SilhouetteExtractor.DRAW_BBOX:
cv2.rectangle(foreground, (x1, y1), (x2, y2), color=(0, 0, 255))
cv2.drawMarker(foreground, SilhouetteExtractor.__to_int_tuple(centroid), (0, 0, 255), cv2.MARKER_CROSS, 11)
bbox_w_h_ratio = tracked_object_stats[cv2.CC_STAT_WIDTH] / tracked_object_stats[cv2.CC_STAT_HEIGHT]
cv2.putText(foreground, "BBOX w/h ratio: {0:.4f}".format(bbox_w_h_ratio), (x1, y1 - 18),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255))
if SilhouetteExtractor.SHOW_INTERSECTS:
if self.intersects_frame_boundary(x1, x2, y1, y2):
cv2.putText(foreground, "FRAME BORDER INTERSECT DETECTED", (0, 54), cv2.FONT_HERSHEY_SIMPLEX, 0.8,
(0, 0, 255))
def get_kinect_angles(image):
"""
Gets angle to goal given an opencv image.
Parameters:
:param: `image` - an opencv image
"""
# print(image)
cv2.imwrite("out/thing.png", image)
thresholded_image = threshold_image_for_tape(numpy.copy(image))
cv2.imwrite("out/threshold.png", thresholded_image)
contours, box = get_contours(thresholded_image)
# total_image = cv2.drawContours(image, [contours], -1, (0, 0, 0))
# random_number = str(int(random.random() * 100))
# print("random number:", random_number)
# cv2.imwrite("out/total_image" + random_number + ".png", total_image)
corners = get_corners_from_contours(contours)
return get_angles_to_goal(get_top_center(corners), image)
arch_light_track.py 文件源码
项目:Vision_Processing-2016
作者: Sabercat-Robotics-4146-FRC
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def get_bounding_rect( cap, win_cap, win, upper, lower):
msk = cv2.dilate(cv2.erode( cv2.inRange( cv2.blur( cv2.cvtColor( cap, cv2.COLOR_BGR2HSV ), (5,5) ), np.array(lower), np.array(upper) ), None, iterations=3), None, iterations=3)
im2, contours, hierarchy = cv2.findContours( msk, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE )
if len(contours) > 0:
areas = [cv2.contourArea(c) for c in contours] # get the area of each contour
max_index = np.argmax(areas) # get the index of the largest contour by area
cnts = contours[max_index] # get the largest contout by area
cv2.drawContours(msk, [cnts], 0, (0,255,0), 3) # Draw the contours to the mask image
x,y,w,h = cv2.boundingRect(cnts) # get the bouding box information about the contour
cv2.rectangle(win_cap,(x,y),(x+w,y+h),(255,255,255),2) # Draw rectangle on the image to represent the bounding box
cv2.imshow( "debug.", win_cap )
try:
self.smt_dash.putNumber('vis_x', x)
self.smt_dash.putNumber('vis_y', y)
self.smt_dash.putNumber('vis_w', w)
self.smt_dash.putNumber('vis_h', h)
except Exception:
pass
image_transformation.py 文件源码
项目:Sign-Language-Recognition
作者: Anmol-Singh-Jaggi
项目源码
文件源码
阅读 44
收藏 0
点赞 0
评论 0
def draw_contours(frame):
"""
Draws a contour around white color.
"""
print("Drawing contour around white color...")
# 'contours' is a list of contours found.
contours, _ = cv2.findContours(
frame, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Finding the contour with the greatest area.
largest_contour_index = find_largest_contour_index(contours)
# Draw the largest contour in the image.
cv2.drawContours(frame, contours,
largest_contour_index, (255, 255, 255), thickness=-1)
# Draw a rectangle around the contour perimeter
contour_dimensions = cv2.boundingRect(contours[largest_contour_index])
# cv2.rectangle(sign_image,(x,y),(x+w,y+h),(255,255,255),0,8)
print("Done!")
return (frame, contour_dimensions)
def get_contours(image, polydb=0.03, contour_range=5, show=False):
# find the contours in the edged image, keeping only the largest ones, and initialize the screen contour
# if cv2version == 3: im2, contours, hierarchy = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range]
# loop over the contours
screenCnt = None
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True) #finds the Contour Perimeter
approx = cv2.approxPolyDP(c, polydb * peri, True)
# if our approximated contour has four points, then we can assume that we have found our screen
if len(approx) == 4:
screenCnt = approx
break
if screenCnt is None: raise EdgeNotFound()
# sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form
if not cv2.isContourConvex(screenCnt):
screenCnt = cv2.convexHull(screenCnt)
x,y,w,h = cv2.boundingRect(screenCnt)
screenCnt = np.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]])
if show: #this is for debugging puposes
new_image = image.copy()
cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2)
cv2.imshow("Contour1 image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return screenCnt
def get_contours(image, polydb=0.03, contour_range=5, show=False):
# find the contours in the edged image, keeping only the largest ones, and initialize the screen contour
if cv2version == 3: im2, contours, hierarchy = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range]
# loop over the contours
screenCnt = None
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True) #finds the Contour Perimeter
approx = cv2.approxPolyDP(c, polydb * peri, True)
# if our approximated contour has four points, then we can assume that we have found our screen
if len(approx) == 4:
screenCnt = approx
break
if screenCnt is None: raise EdgeNotFound()
# sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form
if not cv2.isContourConvex(screenCnt):
screenCnt = cv2.convexHull(screenCnt)
x,y,w,h = cv2.boundingRect(screenCnt)
screenCnt = np.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]])
if show: #this is for debugging puposes
new_image = image.copy()
cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2)
cv2.imshow("Contour1 image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return screenCnt
def get_contours(image, polydb=0.1, contour_range=7, show=False):
# find the contours in the edged image, keeping only the largest ones, and initialize the screen contour
contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range]
# loop over the contours
screenCnt = None
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True) #finds the Contour Perimeter
approx = cv2.approxPolyDP(c, polydb * peri, True)
# if our approximated contour has four points, then we can assume that we have found our screen
if len(approx) == 4:
screenCnt = approx
break
if screenCnt is None:
raise EdgeNotFound()
# sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form
if not cv2.isContourConvex(screenCnt):
screenCnt = cv2.convexHull(screenCnt)
x,y,w,h = cv2.boundingRect(screenCnt)
screenCnt = numpy.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]])
if show: #this is for debugging puposes
new_image = image.copy()
cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2)
cv2.imshow("Contour1 image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return screenCnt
def get_contours(image, polydb=0.03, contour_range=7, show=False):
# find the contours in the edged image, keeping only the largest ones, and initialize the screen contour
# if cv2version == 3: im2, contours, hierarchy = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = _findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(contours, key = cv2.contourArea, reverse = True)[:contour_range]
# loop over the contours
screenCnt = None
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True) #finds the Contour Perimeter
approx = cv2.approxPolyDP(c, polydb * peri, True)
# if our approximated contour has four points, then we can assume that we have found our screen
if len(approx) == 4:
screenCnt = approx
break
if screenCnt is None: raise EdgeNotFound()
# sometimes the algorythm finds a strange non-convex shape. The shape conforms to the card but its not complete, so then just complete the shape into a convex form
if not cv2.isContourConvex(screenCnt):
screenCnt = cv2.convexHull(screenCnt)
x,y,w,h = cv2.boundingRect(screenCnt)
screenCnt = numpy.array([[[x, y]], [[x+w, y]], [[x+w, y+h]], [[x, y+h]]])
if show: #this is for debugging puposes
new_image = image.copy()
cv2.drawContours(new_image, [screenCnt], -1, (255, 255, 0), 2)
cv2.imshow("Contour1 image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return screenCnt
def cropCircle(img):
'''
there many imaged taken thresholded, which means many images is
present as a circle with black surrounded. This function is to
find the largest inscribed rectangle to the thresholed image and
then crop the image to the rectangle.
input: img - the cv2 module
return: img_crop, rectangle, tile_size
'''
if(img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1]*256/img.shape[0]),256)
else:
tile_size = (256, int(img.shape[0]*256/img.shape[1]))
img = cv2.resize(img, dsize=tile_size)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0]
ff = np.zeros((gray.shape[0],gray.shape[1]), 'uint8')
cv2.drawContours(ff, main_contour, -1, 1, 15)
ff_mask = np.zeros((gray.shape[0]+2,gray.shape[1]+2), 'uint8')
cv2.floodFill(ff, ff_mask, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 1)
rect = maxRect(ff)
rectangle = [min(rect[0],rect[2]), max(rect[0],rect[2]), min(rect[1],rect[3]), max(rect[1],rect[3])]
img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]]
cv2.rectangle(ff,(min(rect[1],rect[3]),min(rect[0],rect[2])),(max(rect[1],rect[3]),max(rect[0],rect[2])),3,2)
return [img_crop, rectangle, tile_size]
def cropCircle(img):
'''
there many imaged taken thresholded, which means many images is
present as a circle with black surrounded. This function is to
find the largest inscribed rectangle to the thresholed image and
then crop the image to the rectangle.
input: img - the cv2 module
return: img_crop, rectangle, tile_size
'''
if(img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1]*256/img.shape[0]),256)
else:
tile_size = (256, int(img.shape[0]*256/img.shape[1]))
img = cv2.resize(img, dsize=tile_size)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);
_, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0]
ff = np.zeros((gray.shape[0],gray.shape[1]), 'uint8')
cv2.drawContours(ff, main_contour, -1, 1, 15)
ff_mask = np.zeros((gray.shape[0]+2,gray.shape[1]+2), 'uint8')
cv2.floodFill(ff, ff_mask, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 1)
rect = maxRect(ff)
rectangle = [min(rect[0],rect[2]), max(rect[0],rect[2]), min(rect[1],rect[3]), max(rect[1],rect[3])]
img_crop = img[rectangle[0]:rectangle[1], rectangle[2]:rectangle[3]]
cv2.rectangle(ff,(min(rect[1],rect[3]),min(rect[0],rect[2])),(max(rect[1],rect[3]),max(rect[0],rect[2])),3,2)
return [img_crop, rectangle, tile_size]
def mask_using_contours(img, contours):
"""
Return a copy of the supplied image, where all regions outside the supplied contours have been masked to white.
Args:
img (np.ndarray): the original image
contours (list[np.ndarray]): a list of contours to use when masking
Returns:
np.ndarray: the masked image
"""
img = img.copy()
mask = np.zeros(img.shape, np.uint8)
cv2.drawContours(mask, contours, contourIdx=-1, color=255, thickness=-1)
img[np.where(mask == 0)] = 255
return img
def contours_draw(self, frame, **kwargs):
if 'start' not in kwargs:
kwargs['start'] = 0
if 'end' not in kwargs:
kwargs['end'] = len(self.contours) - 1
if 'color' not in kwargs:
kwargs['color'] = (0, 255, 0)
if 'width' not in kwargs:
kwargs['width'] = 2
contours = [cnt.ndarray for cnt in self.contours][kwargs['start']:kwargs['end'] + 1]
if len(contours) > 0:
cv2.drawContours(frame.ndarray, contours, -1, kwargs['color'], kwargs['width'])
return True
return False
# Dilate this mask's white region
def Q2():
cap = cv2.VideoCapture(0)
while(cap.isOpened() ):
ret = cap.set(3,320)
ret = cap.set(4,240)
ret, frame = cap.read()
if ret==True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
x,thresh = cv2.threshold(gray,137,255,1)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(frame, contours,-1, (0,255,0), 3)
cv2.imshow('Image with contours',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
cv2.destroyAllWindows()
def get_contour_mask(dshape, img_fl):
mask = np.zeros(dshape)
hull = cv2.convexHull(img_fl)
cv2.drawContours(mask, [hull], 0, (1, 1, 1) , -1)
return np.uint8(mask)
# Orients input_ mask onto tmpl_ face
def sizeFiltering(contours):
#this function filters out the smaller retroreflector (as well as any noise) by size
#_, contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
"""blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
cv2.drawContours(blank_image, contours, -1, (255, 255, 255))
cv2.imshow("imagia", blank_image)
cv2.waitKey()"""
if len(contours) == 0:
print "errorrrrr"
return 0
big = contours[0]
for c in contours:
if type(c) and type(big) == np.ndarray:
if cv2.contourArea(c) > cv2.contourArea(big):
big = c
else:
print type(c) and type(big)
return 0
"""blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
cv2.drawContours(blank_image, big, -1, (255, 255, 255))
cv2.imshow("imagia", blank_image)
cv2.waitKey()"""
"""blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
cv2.drawContours(blank_image, big, -1, (255, 255, 255))"""
x,y,w,h = cv2.boundingRect(big)
"""cv2.rectangle(blank_image, (x,y), (x+w, y+h), (255,255,255))
cv2.imshow("rect", blank_image)
cv2.waitKey()"""
return big
def shapeFiltering(img):
contours = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[0]
if len(contours) == 0:
return "yoopsie"
#else:
#print contours
"""blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
cv2.drawContours(blank_image, contours, -1, (255, 255, 255))
cv2.imshow("imagiae", blank_image)
cv2.waitKey()"""
good_shape = []
for c in contours:
x,y,w,h = cv2.boundingRect(c)
"""rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
w = """
#if h == 0:
# continue
ratio = w / h
ratio_grade = ratio / (TMw / TMh)
if 0.2 < ratio_grade < 1.8:
good_shape.append(c)
"""blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
cv2.drawContours(blank_image, good_shape, -1, (255, 255, 255))
cv2.imshow("imagia", blank_image)
cv2.waitKey()"""
return good_shape
def findCorners(contour):
"""blank_image = np.zeros((img.shape[0],img.shape[1],3), np.uint8)
cv2.drawContours(blank_image, contour, -1, (255, 255, 255))
rows,cols = img.shape[0], img.shape[1]
M = cv2.getRotationMatrix2D((cols/2,rows/2),-45,0.5)
dst = cv2.warpAffine(blank_image,M,(cols,rows))
cv2.imshow("rotatio", dst)
cv2.waitKey()"""
rect = cv2.minAreaRect(contour)
box = cv2.boxPoints(rect)
box = np.int0(box)
height_px_1 = box[0][1] - box[3][1]
height_px_2 = box[1][1] - box[2][1]
print height_px_1, height_px_2
if height_px_1 < height_px_2:
close_height_px = height_px_2
far_height_px = height_px_1
else:
close_height_px = height_px_1
far_height_px = height_px_2
return close_height_px, far_height_px