def __bound_contours(roi):
"""
returns modified roi(non-destructive) and rectangles that founded by the algorithm.
@roi region of interest to find contours
@return (roi, rects)
"""
roi_copy = roi.copy()
roi_hsv = cv2.cvtColor(roi, cv2.COLOR_RGB2HSV)
# filter black color
mask1 = cv2.inRange(roi_hsv, np.array([0, 0, 0]), np.array([180, 255, 125]))
mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
mask1 = cv2.Canny(mask1, 100, 300)
mask1 = cv2.GaussianBlur(mask1, (1, 1), 0)
mask1 = cv2.Canny(mask1, 100, 300)
# mask1 = cv2.morphologyEx(mask1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))
# Find contours for detected portion of the image
im2, cnts, hierarchy = cv2.findContours(mask1.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # get largest five contour area
rects = []
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
x, y, w, h = cv2.boundingRect(approx)
if h >= 15:
# if height is enough
# create rectangle for bounding
rect = (x, y, w, h)
rects.append(rect)
cv2.rectangle(roi_copy, (x, y), (x+w, y+h), (0, 255, 0), 1);
return (roi_copy, rects)
python类boundingRect()的实例源码
data_preprocessing_autoencoder.py 文件源码
项目:AVSR-Deep-Speech
作者: pandeydivesh15
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def crop_and_store(frame, mouth_coordinates, name):
"""
Args:
1. frame: The frame which has to be cropped.
2. mouth_coordinates: The coordinates which help in deciding which region is to be cropped.
3. name: The path name to be used for storing the cropped image.
"""
# Find bounding rectangle for mouth coordinates
x, y, w, h = cv2.boundingRect(mouth_coordinates)
mouth_roi = frame[y:y + h, x:x + w]
h, w, channels = mouth_roi.shape
# If the cropped region is very small, ignore this case.
if h < 10 or w < 10:
return
resized = resize(mouth_roi, 32, 32)
cv2.imwrite(name, resized)
def extract_corners(self, image):
"""
Find the 4 corners of a binary image
:param image: binary image
:return: 4 main vertices or None
"""
cnts, _ = cv2.findContours(image.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2:]
cnt = cnts[0]
_, _, h, w = cv2.boundingRect(cnt)
epsilon = min(h, w) * 0.5
vertices = cv2.approxPolyDP(cnt, epsilon, True)
vertices = cv2.convexHull(vertices, clockwise=True)
vertices = self.correct_vertices(vertices)
return vertices
def find_squares(img):
img = cv2.GaussianBlur(img, (5, 5), 0)
squares = []
for gray in cv2.split(img):
for thrs in xrange(0, 255, 26):
if thrs == 0:
bin = cv2.Canny(gray, 0, 50, apertureSize=5)
bin = cv2.dilate(bin, None)
else:
_retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
contours, _hierarchy = find_contours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x, y, w, h = cv2.boundingRect(cnt)
cnt_len = cv2.arcLength(cnt, True)
cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
area = cv2.contourArea(cnt)
if len(cnt) == 4 and 20 < area < 1000 and cv2.isContourConvex(cnt):
cnt = cnt.reshape(-1, 2)
max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
if max_cos < 0.1:
if (1 - (float(w) / float(h)) <= 0.07 and 1 - (float(h) / float(w)) <= 0.07):
squares.append(cnt)
return squares
def affine_skew(self, tilt, phi, img, mask=None):
h, w = img.shape[:2]
if mask is None:
mask = np.zeros((h, w), np.uint8)
mask[:] = 255
A = np.float32([[1, 0, 0], [0, 1, 0]])
if phi != 0.0:
phi = np.deg2rad(phi)
s, c = np.sin(phi), np.cos(phi)
A = np.float32([[c, -s], [s, c]])
corners = [[0, 0], [w, 0], [w, h], [0, h]]
tcorners = np.int32(np.dot(corners, A.T))
x, y, w, h = cv2.boundingRect(tcorners.reshape(1, -1, 2))
A = np.hstack([A, [[-x], [-y]]])
img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
if tilt != 1.0:
s = 0.8*np.sqrt(tilt * tilt - 1)
img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
img = cv2.resize(img, (0, 0), fx=1.0 / tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
A[0] /= tilt
if phi != 0.0 or tilt != 1.0:
h, w = img.shape[:2]
mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST)
Ai = cv2.invertAffineTransform(A)
return img, mask, Ai
def sizeFiltering(contours):
"""
this function filters out the smaller retroreflector (as well as any noise) by size
"""
if len(contours) == 0:
print "sizeFiltering: Error, no contours found"
return 0
big = contours[0]
for c in contours:
if type(c) and type(big) == numpy.ndarray:
if cv2.contourArea(c) > cv2.contourArea(big):
big = c
else:
print type(c) and type(big)
return 0
x,y,w,h = cv2.boundingRect(big)
return big
def profile_score(contour, binary):
"""
Calculate a score based on the "profile" of the target, basically how closely its geometry matches with the expected
geometry of the goal
:param contour:
:param binary:
:return:
"""
bounding = cv2.boundingRect(contour)
pixels = np.zeros((binary.shape[0], binary.shape[1]))
cv2.drawContours(pixels, [contour], -1, 255, -1)
col_averages = np.mean(pixels, axis=0)[bounding[0]:bounding[0] + bounding[2]]
row_averages = np.mean(pixels, axis=1)[bounding[1]:bounding[1] + bounding[3]]
# normalize to between 0 and 1
col_averages *= 1.0 / col_averages.max()
row_averages *= 1.0 / row_averages.max()
col_diff = np.subtract(col_averages, col_profile(col_averages.shape[0], bounding[2]))
row_diff = np.subtract(row_averages, row_profile(row_averages.shape[0], bounding[3]))
# average difference should be close to 0
avg_diff = np.mean([np.mean(col_diff), np.mean(row_diff)])
return 100 - (avg_diff * 50)
def diff_rect(img1, img2, pos=None):
"""find counters include pos in differences between img1 & img2 (cv2 images)"""
diff = cv2.absdiff(img1, img2)
diff = cv2.GaussianBlur(diff, (3, 3), 0)
edges = cv2.Canny(diff, 100, 200)
_, thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
if not contours:
return None
contours.sort(key=lambda c: len(c))
# no pos provide, just return the largest different area rect
if pos is None:
cnt = contours[-1]
x0, y0, w, h = cv2.boundingRect(cnt)
x1, y1 = x0+w, y0+h
return (x0, y0, x1, y1)
# else the rect should contain the pos
x, y = pos
for i in range(len(contours)):
cnt = contours[-1-i]
x0, y0, w, h = cv2.boundingRect(cnt)
x1, y1 = x0+w, y0+h
if x0 <= x <= x1 and y0 <= y <= y1:
return (x0, y0, x1, y1)
def sort_contours(cnts, method="left-to-right"):
# initialize the reverse flag and sort index
reverse = False
i = 0
# handle if we need to sort in reverse
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
# handle if we are sorting against the y-coordinate rather than
# the x-coordinate of the bounding box
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
# construct the list of bounding boxes and sort them from top to
# bottom
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b:b[1][i], reverse=reverse))
# return the list of sorted contours and bounding boxes
return (cnts, boundingBoxes)
def find_contours(self, img):
thresh_img = self.threshold(img)
_, contours, _ = cv2.findContours(thresh_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
result = []
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
if self.draw_approx:
cv2.drawContours(self.out, [approx], -1, self.BLUE, 2, lineType=8)
if len(approx) > 3 and len(approx) < 15:
_, _, w, h = cv2.boundingRect(approx)
if h > self.min_height and w > self.min_width:
hull = cv2.convexHull(cnt)
approx2 = cv2.approxPolyDP(hull,0.01*cv2.arcLength(hull,True),True)
if self.draw_approx2:
cv2.drawContours(self.out, [approx2], -1, self.GREEN, 2, lineType=8)
result.append(approx2)
return result
HandRecognition.py 文件源码
项目:hand-gesture-recognition-opencv
作者: mahaveerverma
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def mark_hand_center(frame_in,cont):
max_d=0
pt=(0,0)
x,y,w,h = cv2.boundingRect(cont)
for ind_y in xrange(int(y+0.3*h),int(y+0.8*h)): #around 0.25 to 0.6 region of height (Faster calculation with ok results)
for ind_x in xrange(int(x+0.3*w),int(x+0.6*w)): #around 0.3 to 0.6 region of width (Faster calculation with ok results)
dist= cv2.pointPolygonTest(cont,(ind_x,ind_y),True)
if(dist>max_d):
max_d=dist
pt=(ind_x,ind_y)
if(max_d>radius_thresh*frame_in.shape[1]):
thresh_score=True
cv2.circle(frame_in,pt,int(max_d),(255,0,0),2)
else:
thresh_score=False
return frame_in,pt,max_d,thresh_score
# 6. Find and display gesture
def diagContour(image):
#Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them
_, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#The contouring operation does some weird stuff to the image so this line just fills the whole thing with black
image.fill(0)
boundingRect = []
firstFail = []
#Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing
for j in [i for i in contours if cv2.contourArea(i) > minArea]:
#br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner
br = cv2.boundingRect(j)
if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol):
boundingRect.append(br)
else:
firstFail.append([br, br[2]/br[3], cv2.contourArea(j)/(br[2]*br[3])])
secondRound = []
for x in range(0, len(boundingRect)):
for y in range(x+1, len(boundingRect)):
i = boundingRect[x]
j = boundingRect[y]
secondRound.append([(x,y,i,j), (abs(i[1]-j[1]), i[3]/2), abs(i[0]-j[0])/i[1]])
for x in secondRound:
if(x[1][0] < x[1][1] and x[2] - GRPASPECT < grpAspectTol):
return [x[0][2], x[0][3]]
return None;
def get_contours(image, polydb=0.1, contour_range=7):
# 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]]])
return screenCnt
def GetImageContour(self):
thresholdImage = self.__convertImagetoBlackWhite() #B & W with adaptive threshold
thresholdImage = cv.Canny(thresholdImage, 100, 200) #Edges by canny edge detection
thresholdImage, contours, hierarchy = cv.findContours(
thresholdImage, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
self.Contours = contours
# uncomment this to see the contours on the image
# cv2.drawContours(thresholdImage, contours, -1, (0,255,0), 3)
# patternFindingObj=PatternFinding()
# areas= [cv.contourArea(contour) for contour in contours]
# for index in xrange(len(contours)):
# IsPattern=self.IsPossibleQRContour(index)
# if IsPattern is True:
# x,y,w,h=cv.boundingRect(contours[index])
# cv.rectangle(self.imageOriginal,(x,y),(x+w,y+h),(0,0,255),2)
# cv.imshow("hello",self.imageOriginal)
# maxAreaIndex=np.argmax(areas)
# x,y,w,h=cv.boundingRect(contours[maxAreaIndex])
# cv.rectangle(self.image2,(x,y),(x+w,y+h),(0,255,0),2)
# cv.imshow("hello",self.imageOriginal)
# cv.waitKey(0)
#cv.destroyAllWindows()
contour_group = (thresholdImage, contours, hierarchy)
return contour_group
def findSquare( self,frame ):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (7, 7), 0)
edged = cv2.Canny(blurred, 60, 60)
# find contours in the edge map
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# loop over our contours to find hexagon
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:50]
screenCnt = None
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.004 * peri, True)
# if our approximated contour has four points, then
# we can assume that we have found our squeare
if len(approx) >= 4:
screenCnt = approx
x,y,w,h = cv2.boundingRect(c)
cv2.drawContours(image, [approx], -1, (0, 0, 255), 1)
#cv2.imshow("Screen", image)
#create the mask and remove rest of the background
mask = np.zeros(image.shape[:2], dtype = "uint8")
cv2.drawContours(mask, [screenCnt], -1, 255, -1)
masked = cv2.bitwise_and(image, image, mask = mask)
#cv2.imshow("Masked",masked )
#crop the masked image to to be compared to referance image
cropped = masked[y:y+h,x:x+w]
#scale the image so it is fixed size as referance image
cropped = cv2.resize(cropped, (200,200), interpolation =cv2.INTER_AREA)
return cropped
def extract_corners(self, image):
"""
Find the 4 corners of a binary image
:param image: binary image
:return: 4 main vertices or None
"""
cnts, _ = cv2.findContours(image.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2:]
cnt = cnts[0]
_, _, h, w = cv2.boundingRect(cnt)
epsilon = min(h, w) * 0.5
o_vertices = cv2.approxPolyDP(cnt, epsilon, True)
vertices = cv2.convexHull(o_vertices, clockwise=True)
vertices = self.correct_vertices(vertices)
if self.debug:
temp = cv2.cvtColor(image.copy(), cv2.COLOR_GRAY2BGR)
cv2.drawContours(temp, cnts, -1, (0, 255, 0), 10)
cv2.drawContours(temp, o_vertices, -1, (255, 0, 0), 30)
cv2.drawContours(temp, vertices, -1, (0, 0, 255), 20)
self.save2image(temp)
return vertices
def diff_rect(img1, img2, pos=None):
"""find counters include pos in differences between img1 & img2 (cv2 images)"""
diff = cv2.absdiff(img1, img2)
diff = cv2.GaussianBlur(diff, (3, 3), 0)
edges = cv2.Canny(diff, 100, 200)
_, thresh = cv2.threshold(edges, 0, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
if not contours:
return None
contours.sort(key=lambda c: len(c))
# no pos provide, just return the largest different area rect
if pos is None:
cnt = contours[-1]
x0, y0, w, h = cv2.boundingRect(cnt)
x1, y1 = x0+w, y0+h
return (x0, y0, x1, y1)
# else the rect should contain the pos
x, y = pos
for i in range(len(contours)):
cnt = contours[-1-i]
x0, y0, w, h = cv2.boundingRect(cnt)
x1, y1 = x0+w, y0+h
if x0 <= x <= x1 and y0 <= y <= y1:
return (x0, y0, x1, y1)
def find_chars(img):
gray = np.array(img.convert("L"))
ret, mask = cv2.threshold(gray, 180, 255, cv2.THRESH_BINARY)
image_final = cv2.bitwise_and(gray, gray, mask=mask)
ret, new_img = cv2.threshold(image_final, 180, 255, cv2.THRESH_BINARY_INV)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
dilated = cv2.dilate(new_img, kernel, iterations=1)
# Image.fromarray(dilated).save('out.png') # for debugging
_, contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
coords = []
for contour in contours:
# get rectangle bounding contour
[x, y, w, h] = cv2.boundingRect(contour)
# ignore large chars (probably not chars)
if w > 70 and h > 70:
continue
coords.append((x, y, w, h))
return coords
# find list of eye coordinates in image
def keep_box(contour):
xx, yy, w_, h_ = cv2.boundingRect(contour)
# width and height need to be floats
w_ *= 1.0
h_ *= 1.0
# Test it's shape - if it's too oblong or tall it's
# probably not a real character
if w_ / h_ < 0.1 or w_ / h_ > 10:
if DEBUG:
print "\t Rejected because of shape: (" + str(xx) + "," + str(yy) + "," + str(w_) + "," + str(h_) + ")" + \
str(w_ / h_)
return False
# check size of the box
if ((w_ * h_) > ((img_x * img_y) / 5)) or ((w_ * h_) < 15):
if DEBUG:
print "\t Rejected because of size"
return False
return True
def test_initial_pass_through_compare(self):
original = cv2.imread(os.path.join(self.provider.assets, "start_screen.png"))
against = self.provider.get_img_from_screen_shot()
wrong = cv2.imread(os.path.join(self.provider.assets, "battle.png"))
# convert the images to grayscale
original = mask_image([127], [255], cv2.cvtColor(original, cv2.COLOR_BGR2GRAY), True)
against = mask_image([127], [255], cv2.cvtColor(against, cv2.COLOR_BGR2GRAY), True)
wrong = mask_image([127], [255], cv2.cvtColor(wrong, cv2.COLOR_BGR2GRAY), True)
# initialize the figure
(score, diff) = compare_ssim(original, against, full=True)
diff = (diff * 255).astype("uint8")
self.assertTrue(score > .90, 'If this is less then .90 the initial compare of the app will fail')
(score, nothing) = compare_ssim(original, wrong, full=True)
self.assertTrue(score < .90)
if self.__debug_pictures__:
# threshold the difference image, followed by finding contours to
# obtain the regions of the two input images that differ
thresh = cv2.threshold(diff, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0]
# loop over the contours
for c in cnts:
# compute the bounding box of the contour and then draw the
# bounding box on both input images to represent where the two
# images differ
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(original, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.rectangle(against, (x, y), (x + w, y + h), (0, 0, 255), 2)
# show the output images
diffs = ("Original", original), ("Modified", against), ("Diff", diff), ("Thresh", thresh)
images = ("Original", original), ("Against", against), ("Wrong", wrong)
self.setup_compare_images(diffs)
self.setup_compare_images(images)
def draw_contours(self):
""""""
# contours all the objects found
# (findContours changes the source image,
# hence copy)
contours, _ = cv2.findContours(self.mask.copy(),
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# rectangles
for contour in contours:
size = cv2.contourArea(contour)
if size > self.threshold: # only larger objects
ret_x, ret_y, ret_w, ret_h = cv2.boundingRect(contour)
cv2.rectangle(self.display, (ret_x, ret_y),
(ret_x+ret_w,
ret_y+ret_h),
(0, 255, 255), 2)
def remove_border(contour, ary):
"""Remove everything outside a border contour."""
# Use a rotated rectangle (should be a good approximation of a border).
# If it's far from a right angle, it's probably two sides of a border and
# we should use the bounding box instead.
c_im = np.zeros(ary.shape)
r = cv2.minAreaRect(contour)
degs = r[2]
if angle_from_right(degs) <= 10.0:
box = cv2.boxPoints(r)
box = np.int0(box)
cv2.drawContours(c_im, [box], 0, 255, -1)
cv2.drawContours(c_im, [box], 0, 0, 4)
else:
x1, y1, x2, y2 = cv2.boundingRect(contour)
cv2.rectangle(c_im, (x1, y1), (x2, y2), 255, -1)
cv2.rectangle(c_im, (x1, y1), (x2, y2), 0, 4)
return np.minimum(c_im, ary)
def _find_size_candidates(self, image):
binary_image = self._filter_image(image)
_, contours, _ = cv2.findContours(binary_image,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_SIMPLE)
size_candidates = []
for contour in contours:
bounding_rect = cv2.boundingRect(contour)
contour_area = cv2.contourArea(contour)
if self._is_valid_contour(contour_area, bounding_rect):
candidate = (bounding_rect[2] + bounding_rect[3]) / 2
size_candidates.append(candidate)
return size_candidates
def keep_box(contour):
xx, yy, w_, h_ = cv2.boundingRect(contour)
# width and height need to be floats
w_ *= 1.0
h_ *= 1.0
# Test it's shape - if it's too oblong or tall it's
# probably not a real character
if w_ / h_ < 0.1 or w_ / h_ > 10:
if DEBUG:
print "\t Rejected because of shape: (" + str(xx) + "," + str(yy) + "," + str(w_) + "," + str(h_) + ")" + \
str(w_ / h_)
return False
# check size of the box
if ((w_ * h_) > ((img_x * img_y) / 5)) or ((w_ * h_) < 15):
if DEBUG:
print "\t Rejected because of size"
return False
return True
def keepBox(contour):
xx, yy, w_, h_ = cv2.boundingRect(contour)
# width and height need to be floats
w_ *= 1.0
h_ *= 1.0
# Test it's shape - if it's too oblong or tall it's
# probably not a real character
if w_ / h_ < 0.1 or w_ / h_ > 10:
if DEBUG:
print "\t Rejected because of shape: (" + str(xx) + "," + str(yy) + "," + str(w_) + "," + str(h_) + ")" + \
str(w_ / h_)
return False
# check size of the box
if ((w_ * h_) > ((img_x * img_y) / 5)) or ((w_ * h_) < 15):
if DEBUG:
print "\t Rejected because of size"
return False
return True
# whether contour is a child
def findIDcnt(countours):
#????????
widths = []
for idx, cnt in enumerate(countours):
x, y, width, height = cv2.boundingRect(cnt)
widths.insert(idx, width)
#???????????
IDList = heapq.nlargest(3, widths)
#???????????????????
IDcnts = []
for idx, item in enumerate(IDList):
index = widths.index(item)
IDcnts.insert(idx, countours[index])
# print IDcnts
return IDcnts
# ????
def contourImg(image):
#Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them
_, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#The contouring operation does some weird stuff to the image so this line just fills the whole thing with black
image.fill(0)
boundingRect = []
#Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing
for j in [i for i in contours if cv2.contourArea(i) > minArea]:
#br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner
br = cv2.boundingRect(j)
if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol):
boundingRect.append(br)
for x in range(0, len(boundingRect)):
for y in range(x+1, len(boundingRect)):
i = boundingRect[x]
j = boundingRect[y]
if(abs(i[1]-j[1]) < i[3]/2) and abs(abs(i[0]-j[0])/i[1] - GRPASPECT) < grpAspectTol:
return [createRectCnt(i), createRectCnt(j)]
return None
def diagContour(image):
#Find contours in the image the first and last returns dont matter so the _ is just a placeholder to ignore them
_, contours, _ = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#The contouring operation does some weird stuff to the image so this line just fills the whole thing with black
image.fill(0)
boundingRect = []
firstFail = []
#Loops through all contours bigger than minArea pixels. That number is tweakable and determined by testing
for j in [i for i in contours if cv2.contourArea(i) > minArea]:
#br is a (list/tuple)? of the form x, y, width, height where (x,y) is the (top/bottom)? (left/right)? corner
br = cv2.boundingRect(j)
if(abs(br[2]/br[3] - INDASPECT) < indAspectTol and cv2.contourArea(j)/(br[2]*br[3]) > covTol):
boundingRect.append(br)
else:
firstFail.append([br, br[2]/br[3], cv2.contourArea(j)/(br[2]*br[3])])
secondRound = []
for x in range(0, len(boundingRect)):
for y in range(x+1, len(boundingRect)):
i = boundingRect[x]
j = boundingRect[y]
secondRound.append([(x,y,i,j), (abs(i[1]-j[1]), i[3]/2), abs(i[0]-j[0])/i[1]])
for x in secondRound:
if(x[1][0] < x[1][1] and x[2] - GRPASPECT < grpAspectTol):
return firstFail, secondRound, [createRectCnt(x[0][2]), createRectCnt(x[0][3])]
return firstFail, secondRound, None
def boundingRects(scale, contours):
for contour in contours:
epsilon = 0.1 * cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, epsilon, True)
x, y, w, h = cv2.boundingRect(approx)
yield [x * scale, y * scale, w * scale, h * scale]
def plateDetect(img,img2):
'''?????????????????'''
im2, contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for con in contours:
x,y,w,h=cv2.boundingRect(con)
area=w*h
ratio=w/h
if ratio>2 and ratio<4 and area>=2000 and area<=25000:
logo_y1=max(0,int(y-h*3.0))
logo_y2=y
logo_x1=x
logo_x2=x+w
img_logo=img2.copy()
logo=img_logo[logo_y1:logo_y2,logo_x1:logo_x2]
cv2.imwrite('./logo1.jpg',logo)
cv2.rectangle(img2,(x,y),(x+w,y+h),(255,0,0),2)
cv2.rectangle(img2,(logo_x1,logo_y1),(logo_x2,logo_y2),(0,255,0),2)
global plate
plate=[x,y,w,h]
#?????????
return logo