def findbodies(image, faces):
bodies = np.zeros_like(faces)
bodiesindex = 0
#for each face, draw a body
for (x, y, facewidth, faceheight) in faces:
#3*faceheight, 7/3 * facewidth, .5*faceheight below the face.
bodyheight = 3 * faceheight
bodywidth = 7/3 * facewidth
y_body = y + faceheight + .5 * faceheight
x_body = x + .5 * facewidth - .5 * bodywidth
bodies[bodiesindex] = (x_body,y_body, bodywidth, bodyheight)
bodiesindex = bodiesindex + 1
#cv2.rectangle(image, (x_body, y_body), (x_body+bodywidth, y_body+bodyheight), (0, 255, 0), 2)
return bodies
python类rectangle()的实例源码
def verify_sizes(rectangle):
# print candidate
# help(cv2.minAreaRect)
(x, y), (width, height), rect_angle = rectangle
# Calculate angle and discard rects that has been rotated more than 15 degrees
angle = 90 - rect_angle if (width < height) else -rect_angle
if 15 < abs(angle) < 165: # 180 degrees is maximum
return False
# We make basic validations about the regions detected based on its area and aspect ratio.
# We only consider that a region can be a plate if the aspect ratio is approximately 520/110 = 4.727272
# (plate width divided by plate height) with an error margin of 40 percent
# and an area based on a minimum of 15 pixels and maximum of 125 pixels for the height of the plate.
# These values are calculated depending on the image sizes and camera position:
area = height * width
if height == 0 or width == 0:
return False
if not satisfy_ratio(area, width, height):
return False
return True
def make_mouse_callback(imgs, ref_pt):
# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
cropping = [False]
clone = imgs[0]
def _click_and_crop(event, x, y, flags, param):
# grab references to the global variables
# global ref_pt, cropping
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
ref_pt[0] = (x, y)
cropping[0] = True
# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates and indicate that
# the cropping operation is finished
ref_pt[1] = (x, y)
cropping[0] = False
# draw a rectangle around the region of interest
imgs[1] = image = clone.copy()
cv2.rectangle(image, ref_pt[0], ref_pt[1], (0, 255, 0), 2)
cv2.imshow("image", image)
elif event == cv2.EVENT_MOUSEMOVE and cropping[0]:
img2 = clone.copy()
cv2.rectangle(img2, ref_pt[0], (x, y), (0, 255, 0), 2)
imgs[1] = image = img2
cv2.imshow("image", image)
return _click_and_crop
def draw_boxes(im, bboxes, is_display=True, color=None, caption="Image", wait=True):
"""
boxes: bounding boxes
"""
im=im.copy()
for box in bboxes:
if color==None:
if len(box)==5 or len(box)==9:
c=tuple(cm.jet([box[-1]])[0, 2::-1]*255)
else:
c=tuple(np.random.randint(0, 256, 3))
else:
c=color
cv2.rectangle(im, tuple(box[:2]), tuple(box[2:4]), c)
if is_display:
cv2.imshow(caption, im)
if wait:
cv2.waitKey(0)
return im
def find_faces(self, image, draw_box=False):
"""Uses a haarcascade to detect faces inside an image.
Args:
image: The image.
draw_box: If True, the image will be marked with a rectangle.
Return:
The faces as returned by OpenCV's detectMultiScale method for
cascades.
"""
frame_gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
faces = self.cascade.detectMultiScale(
frame_gray,
scaleFactor=1.3,
minNeighbors=5,
minSize=(50, 50),
flags=0)
if draw_box:
for x, y, w, h in faces:
cv2.rectangle(image, (x, y),
(x + w, y + h), (0, 255, 0), 2)
return faces
def cropCircle(img, resize=None):
if resize:
if (img.shape[0] > img.shape[1]):
tile_size = (int(img.shape[1] * resize / img.shape[0]), resize)
else:
tile_size = (resize, int(img.shape[0] * resize / img.shape[1]))
img = cv2.resize(img, dsize=tile_size, interpolation=cv2.INTER_CUBIC)
else:
tile_size = img.shape
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 draw_result(out, im_scale, clss, bbox, nms_thresh, conf):
CV_AA = 16
for cls_id in range(1, 21):
_cls = clss[:, cls_id][:, np.newaxis]
_bbx = bbox[:, cls_id * 4: (cls_id + 1) * 4]
dets = np.hstack((_bbx, _cls))
keep = nms(dets, nms_thresh)
dets = dets[keep, :]
inds = np.where(dets[:, -1] >= conf)[0]
for i in inds:
x1, y1, x2, y2 = map(int, dets[i, :4])
cv.rectangle(out, (x1, y1), (x2, y2), (0, 0, 255), 2, CV_AA)
ret, baseline = cv.getTextSize(
CLASSES[cls_id], cv.FONT_HERSHEY_SIMPLEX, 0.8, 1)
cv.rectangle(out, (x1, y2 - ret[1] - baseline),
(x1 + ret[0], y2), (0, 0, 255), -1)
cv.putText(out, CLASSES[cls_id], (x1, y2 - baseline),
cv.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 1, CV_AA)
return out
def test_generate_proposals(self):
self.assertEqual(self.total_anchors, len(self.shifts) *
self.anchor_target_layer.anchors.shape[0])
min_x = self.all_anchors[:, 0].min()
min_y = self.all_anchors[:, 1].min()
max_x = self.all_anchors[:, 2].max()
max_y = self.all_anchors[:, 3].max()
canvas = np.zeros(
(int(abs(min_y) + max_y) + 1,
int(abs(min_x) + max_x) + 1), dtype=np.uint8)
self.all_anchors[:, 0] -= min_x
self.all_anchors[:, 1] -= min_y
self.all_anchors[:, 2] -= min_x
self.all_anchors[:, 3] -= min_y
for anchor in self.all_anchors:
anchor = list(six.moves.map(int, anchor))
cv.rectangle(
canvas, (anchor[0], anchor[1]), (anchor[2], anchor[3]), 255)
cv.imwrite('tests/all_anchors.png', canvas)
def test_keep_inside(self):
inds_inside, anchors = self.inds_inside, self.anchors
min_x = anchors[:, 0].min()
min_y = anchors[:, 1].min()
max_x = anchors[:, 2].max()
max_y = anchors[:, 3].max()
canvas = np.zeros(
(int(max_y - min_y) + 1,
int(max_x - min_x) + 1), dtype=np.uint8)
anchors[:, 0] -= min_x
anchors[:, 1] -= min_y
anchors[:, 2] -= min_x
anchors[:, 3] -= min_y
for i, anchor in enumerate(anchors):
anchor = list(six.moves.map(int, anchor))
_canvas = np.zeros(
(int(max_y - min_y) + 1,
int(max_x - min_x) + 1), dtype=np.uint8)
cv.rectangle(
_canvas, (anchor[0], anchor[1]), (anchor[2], anchor[3]), 255)
cv.rectangle(
canvas, (anchor[0], anchor[1]), (anchor[2], anchor[3]), 255)
cv.imwrite('tests/anchors_inside_{}.png'.format(i), _canvas)
cv.imwrite('tests/anchors_inside.png'.format(i), canvas)
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 detect(imgfile):
origimg = cv2.imread(imgfile)
img = preprocess(origimg)
img = img.astype(np.float32)
img = img.transpose((2, 0, 1))
net.blobs['data'].data[...] = img
out = net.forward()
box, conf, cls = postprocess(origimg, out)
for i in range(len(box)):
p1 = (box[i][0], box[i][1])
p2 = (box[i][2], box[i][3])
cv2.rectangle(origimg, p1, p2, (0,255,0))
p3 = (max(p1[0], 15), max(p1[1], 15))
title = "%s:%.2f" % (CLASSES[int(cls[i])], conf[i])
cv2.putText(origimg, title, p3, cv2.FONT_ITALIC, 0.6, (0, 255, 0), 1)
cv2.imshow("SSD", origimg)
k = cv2.waitKey(0) & 0xff
#Exit if ESC pressed
if k == 27 : return False
return True
def make_mouse_callback(imgs, ref_pt):
# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
cropping = [False]
clone = imgs[0]
def _click_and_crop(event, x, y, flags, param):
# grab references to the global variables
# global ref_pt, cropping
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
ref_pt[0] = (x, y)
cropping[0] = True
# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates and indicate that
# the cropping operation is finished
ref_pt[1] = (x, y)
cropping[0] = False
# draw a rectangle around the region of interest
imgs[1] = image = clone.copy()
cv2.rectangle(image, ref_pt[0], ref_pt[1], (0, 255, 0), 2)
cv2.imshow("image", image)
elif event == cv2.EVENT_MOUSEMOVE and cropping[0]:
img2 = clone.copy()
cv2.rectangle(img2, ref_pt[0], (x, y), (0, 255, 0), 2)
imgs[1] = image = img2
cv2.imshow("image", image)
return _click_and_crop
def locate_img(image, template):
img = image.copy()
res = cv2.matchTemplate(img, template, method)
print res
print res.shape
cv2.imwrite('image/shape.png', res)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
print cv2.minMaxLoc(res)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
h, w = template.shape
bottom_right = (top_left[0] + w, top_left[1]+h)
cv2.rectangle(img, top_left, bottom_right, 255, 2)
cv2.imwrite('image/tt.jpg', img)
extract_signals.py 文件源码
项目:traffic-light-detection
作者: ranveeraggarwal
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def click_and_crop(event, x, y, flags, param):
# grab references to the global variables
global refPt, cropping, i
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
if refPt == []:
refPt = [(x, y)]
else:
refPt.append((x,y))
cropping = True
i += 1
if event == cv2.EVENT_MOUSEMOVE and cropping:
image2 = image.copy()
cv2.rectangle(image2, refPt[2*i-2], (x,y), (0,255,0), 2)
cv2.imshow("image",image2)
# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates and indicate that
# the cropping operation is finished
refPt.append((x, y))
cropping = False
# draw a rectangle around the region of interest
cv2.rectangle(image, refPt[2*i-2], refPt[2*i-1], (0, 255, 0), 2)
# cv2.rectangle(image2, refPt[2*i-2], refPt[2*i-1], (0, 255, 0), 2)
cv2.imshow("image", image)
# construct the argument parser and parse the arguments
def showRegions(self):
output = self.origin_image.copy()
for r in range(0, np.shape(self.regions)[0]):
rect = self.regions[r]
cv2.rectangle(output,
(rect[0],rect[1]),
(rect[0]+rect[2],
rect[1]+rect[3]),
(0, 255, 0), 2)
cv2.rectangle(output,
(rect[0],rect[1]),
(rect[0]+rect[2],
rect[1]+rect[3]),
(255, 0, 0), 1)
return output
#--------------------------------------------------------
#--------------------------------------------------------
# Class provide an interface to perform OCR
def draw_rects(img, rects, color):
"""
?????????????
:param img:
:param rects:
:param color:
:return:
"""
for x, y, w, h in rects:
face = img[x:x+w,y:y+h]
face = cv2.resize(face,(224,224))
if gender.predict(face)==1:
text = "Male"
else:
text = "Female"
cv2.rectangle(img, (x, y), (w, h), color, 2)
cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), lineType=cv2.LINE_AA)
searchObject.py 文件源码
项目:object-detection-with-deep-learning
作者: neerajdixit
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def draw_labeled_bboxes(img, labels):
"""
Draw the boxes around detected object.
"""
# Iterate through all detected cars
for car_number in range(1, labels[1]+1):
# Find pixels with each car_number label value
nonzero = (labels[0] == car_number).nonzero()
# Identify x and y values of those pixels
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Define a bounding box based on min/max x and y
bbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))
# Draw the box on the image
cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 6)
return img
def draw_countdown(self, frame):
# Draw the count "3..".
countdown_x_offset = 1 + self.countdown # Offset from left edge
countdown_x = int(self.screenwidth -
(self.screenwidth / 5) * countdown_x_offset)
self.overlay = frame.copy()
countdown_panel_y1 = int(self.screenheight * (4. / 5))
cv2.rectangle(self.overlay, (0, countdown_panel_y1),
(self.screenwidth, self.screenheight), (224, 23, 101), -1)
cv2.addWeighted(self.overlay, OPACITY, frame,
1 - OPACITY, 0, frame)
countdown_y_offset = 20
countdown_y = int((self.screenheight * 7. / 8) + countdown_y_offset)
countdown_coord = (countdown_x, countdown_y)
draw_text(countdown_coord, frame, str(self.countdown))
return frame
def random_augment_image(image, row):
# start0_max, end0_max, start1_max, end1_max = get_bounding_boxes_positions(image, row)
# image = cv2.rectangle(image, (int(start1_max), int(start0_max)), (int(end1_max), int(end0_max)), (0, 0, 255), thickness=5)
if random.randint(0, 1) == 0:
image = return_random_crop(image, row)
else:
image = return_random_perspective(image, row)
image = random_rotate(image)
# all possible mirroring and flips (in total there are only 8 possible configurations)
mirror = random.randint(0, 1)
if mirror != 0:
image = image[::-1, :, :]
angle = random.randint(0, 3)
if angle != 0:
image = np.rot90(image, k=angle)
image = lightning_change(image)
image = blur_image(image)
return image
def grabcutbb(im, bbv):
mask = np.full(im.shape[:2],cv2.GC_PR_BGD,np.uint8)
for bb in bbv:
if bb[4]:
cv2.rectangle(mask, (bb[0], bb[1]), (bb[2], bb[3]), int(cv2.GC_FGD), -1)
else:
cv2.rectangle(mask, (bb[0], bb[1]), (bb[2], bb[3]), int(cv2.GC_BGD), -1)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (0, im.shape[:2][0]/2, im.shape[:2][1], im.shape[:2][0])
cv2.grabCut(im, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_MASK)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
return mask2