def render_lane(image, corners, ploty, fitx, ):
_, src, dst = perspective_transform(image, corners)
Minv = cv2.getPerspectiveTransform(dst, src)
# Create an image to draw the lines on
warp_zero = np.zeros_like(image[:,:,0]).astype(np.uint8)
color_warp = np.dstack((warp_zero, warp_zero, warp_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts = np.vstack((fitx,ploty)).astype(np.int32).T
# Draw the lane onto the warped blank image
#plt.plot(left_fitx, ploty, color='yellow')
cv2.polylines(color_warp, [pts], False, (0, 255, 0), 10)
#cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
newwarp = cv2.warpPerspective(color_warp, Minv, (image.shape[1], image.shape[0]))
# Combine the result with the original image
result = cv2.addWeighted(image, 1, newwarp, 0.3, 0)
return result
python类addWeighted()的实例源码
def findCircles(fname, image, circles_directory):
f = os.path.join(circles_directory, os.path.basename(fname) + ".pkl")
if os.path.exists(f):
circles = pickle.load(open(f, "rb"))
return circles
image_cols, image_rows, _ = image.shape
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.bilateralFilter(gray, 9, 75, 75)
gray = cv2.addWeighted(gray, 1.5, blurred, -0.5, 0)
gray = cv2.bilateralFilter(gray, 9, 75, 75)
# # detect circles in the image
dp = 1
c1 = 100
c2 = 15
print "start hough", fname
circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, dp, image_cols / 8, param1=c1, param2=c2)
print "finish hough", fname
pickle.dump(circles, open(f, "wb"))
if circles is None or not len(circles):
return None
return circles
def transparent_circle(img,center,radius,color,thickness):
center = tuple(map(int,center))
rgb = [255*c for c in color[:3]] # convert to 0-255 scale for OpenCV
alpha = color[-1]
radius = int(radius)
if thickness > 0:
pad = radius + 2 + thickness
else:
pad = radius + 3
roi = slice(center[1]-pad,center[1]+pad),slice(center[0]-pad,center[0]+pad)
try:
overlay = img[roi].copy()
cv2.circle(img,center,radius,rgb, thickness=thickness, lineType=cv2.LINE_AA)
opacity = alpha
cv2.addWeighted(src1=img[roi], alpha=opacity, src2=overlay, beta=1. - opacity, gamma=0, dst=img[roi])
except:
logger.debug("transparent_circle would have been partially outside of img. Did not draw it.")
data_preprocessing_autoencoder.py 文件源码
项目:AVSR-Deep-Speech
作者: pandeydivesh15
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def visualize(frame, coordinates_list, alpha = 0.80, color=[255, 255, 255]):
"""
Args:
1. frame: OpenCV's image which has to be visualized.
2. coordinates_list: List of coordinates which will be visualized in the given `frame`
3. alpha, color: Some parameters which help in visualizing properly.
A convex hull will be shown for each element in the `coordinates_list`
"""
layer = frame.copy()
output = frame.copy()
for coordinates in coordinates_list:
c_hull = cv2.convexHull(coordinates)
cv2.drawContours(layer, [c_hull], -1, color, -1)
cv2.addWeighted(layer, alpha, output, 1 - alpha, 0, output)
cv2.imshow("Output", output)
def create_heatmaps(img, pred):
"""
Uses objectness probability to draw a heatmap on the image and returns it
"""
# find anchors with highest prediction
best_pred = np.max(pred[..., 0], axis=-1)
# convert probabilities to colormap scale
best_pred = np.uint8(best_pred * 255)
# apply color map
# cv2 colormaps create BGR, not RGB
cmap = cv2.cvtColor(cv2.applyColorMap(best_pred, cv2.COLORMAP_JET), cv2.COLOR_BGR2RGB)
# resize the color map to fit image
cmap = cv2.resize(cmap, img.shape[1::-1], interpolation=cv2.INTER_NEAREST)
# overlay cmap with image
return cv2.addWeighted(cmap, 1, img, 0.5, 0)
def transparent_image_overlay(pos,overlay_img,img,alpha):
"""
Overlay one image with another with alpha blending
In player this will be used to overlay the eye (as overlay_img) over the world image (img)
Arguments:
pos: (x,y) position of the top left corner in numpy row,column format from top left corner (numpy coord system)
overlay_img: image to overlay
img: destination image
alpha: 0.0-1.0
"""
roi = slice(pos[1],pos[1]+overlay_img.shape[0]),slice(pos[0],pos[0]+overlay_img.shape[1])
try:
cv2.addWeighted(overlay_img,alpha,img[roi],1.-alpha,0,img[roi])
except:
logger.debug("transparent_image_overlay was outside of the world image and was not drawn")
pass
def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output
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
photo_exif_date_print.py 文件源码
项目:python-image-processing
作者: karaage0703
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def put_date(file, date):
base_img_cv2 = cv2.imread(file)
base_img = Image.open(file).convert('RGBA')
txt = Image.new('RGB', base_img.size, (0, 0, 0))
draw = ImageDraw.Draw(txt)
fnt = ImageFont.truetype('./Arial Black.ttf', size=(int)((base_img.size[0]+base_img.size[1])/100))
textw, texth = draw.textsize(date, font=fnt)
draw.text(((base_img.size[0]*0.95 - textw) , (base_img.size[1]*0.95 - texth)),
date, font=fnt, fill=font_color)
txt_array = np.array(txt)
output_img = cv2.addWeighted(base_img_cv2, 1.0, txt_array, 1.0, 0)
return output_img
def draw_debug(img, pose, gt_pose, tracker, alpha, debug_info):
if debug_info is not None:
img_render, bb, _ = debug_info
img_render = cv2.resize(img_render, (bb[2, 1] - bb[0, 1], bb[1, 0] - bb[0, 0]))
crop = img[bb[0, 0]:bb[1, 0], bb[0, 1]:bb[2, 1], :]
h, w, c = crop.shape
blend = image_blend(img_render[:h, :w, ::-1], crop)
img[bb[0, 0]:bb[1, 0], bb[0, 1]:bb[2, 1], :] = cv2.addWeighted(img[bb[0, 0]:bb[1, 0], bb[0, 1]:bb[2, 1], :],
1 - alpha, blend, alpha, 1)
else:
axis = compute_axis(pose, tracker.camera, tracker.object_width, scale=(1000, -1000, -1000))
axis_gt = compute_axis(gt_pose, tracker.camera, tracker.object_width, scale=(1000, -1000, -1000))
cv2.line(img, tuple(axis_gt[0, ::-1]), tuple(axis_gt[1, ::-1]), (0, 0, 155), 3)
cv2.line(img, tuple(axis_gt[0, ::-1]), tuple(axis_gt[2, ::-1]), (0, 155, 0), 3)
cv2.line(img, tuple(axis_gt[0, ::-1]), tuple(axis_gt[3, ::-1]), (155, 0, 0), 3)
cv2.line(img, tuple(axis[0, ::-1]), tuple(axis[1, ::-1]), (0, 0, 255), 3)
cv2.line(img, tuple(axis[0, ::-1]), tuple(axis[2, ::-1]), (0, 255, 0), 3)
cv2.line(img, tuple(axis[0, ::-1]), tuple(axis[3, ::-1]), (255, 0, 0), 3)
def draw_labels(img, labels, label_colors, convert=True):
"""
Draw the labels on top of the input image
:param img: the image being classified
:param labels: the output of the neural network
:param label_colors: the label color map defined in the source
:param convert: should the output be converted to RGB
"""
labels_colored = np.zeros_like(img)
for label in label_colors:
label_mask = labels == label
labels_colored[label_mask] = label_colors[label]
img = cv2.addWeighted(img, 1, labels_colored, 0.8, 0)
if not convert:
return img
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#-------------------------------------------------------------------------------
def put_date(file, date):
base_img_cv2 = cv2.imread(file)
base_img = Image.open(file).convert('RGBA')
txt = Image.new('RGB', base_img.size, (0, 0, 0))
draw = ImageDraw.Draw(txt)
fnt = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMono.ttf', size=(int)((base_img.size[0]+base_img.size[1])/100))
textw, texth = draw.textsize(date, font=fnt)
draw.text(((base_img.size[0]*0.95 - textw) , (base_img.size[1]*0.95 - texth)),
date, font=fnt, fill=font_color)
txt_array = np.array(txt)
output_img = cv2.addWeighted(base_img_cv2, 1.0, txt_array, 1.0, 0)
return output_img
def img_sobel_binary(im, blur_sz):
# ??????????????
img_blur = cv2.GaussianBlur(im,blur_sz,0)
if len(img_blur.shape) == 3:
blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)
else:
blur_gray = img_blur
# ??Sobel????
sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3)
abs_sobelx = np.absolute(sobelx)
sobel_8u = np.uint8(abs_sobelx)
img_show_hook("Sobel??", sobel_8u)
# OTSU??????
ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thd_abs = cv2.convertScaleAbs(thd)
bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0)
img_show_hook("OTSU????", bgimg)
return bgimg
def img_sobel_binary(im, blur_sz):
# ??????????????
img_blur = cv2.GaussianBlur(im,blur_sz,0)
if len(img_blur.shape) == 3:
blur_gray = cv2.cvtColor(img_blur,cv2.COLOR_BGR2GRAY)
else:
blur_gray = img_blur
# ??Sobel????
sobelx = cv2.Sobel(blur_gray,cv2.CV_16S,1,0,ksize=3)
abs_sobelx = np.absolute(sobelx)
sobel_8u = np.uint8(abs_sobelx)
img_show_hook("Sobel??", sobel_8u)
# OTSU??????
ret, thd = cv2.threshold(sobel_8u, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thd_abs = cv2.convertScaleAbs(thd)
bgimg = cv2.addWeighted(thd_abs, 1, 0, 0, 0)
img_show_hook("OTSU????", bgimg)
return bgimg
def findCircles(image):
image_cols, image_rows, _ = image.shape
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
first, second = getRescaledDimensions(gray.shape[1], gray.shape[0], HD_MAX_X, HD_MAX_Y)
gray = cv2.resize(gray, (first, second))
blurred = cv2.bilateralFilter(gray, 9, 75, 75)
gray = cv2.addWeighted(gray, 1.5, blurred, -0.5, 0)
gray = cv2.bilateralFilter(gray, 9, 75, 75)
# # detect circles in the image
dp = 1
c1 = 100
c2 = 15
circles = cv2.HoughCircles(gray, cv2.cv.CV_HOUGH_GRADIENT, dp, second / 8, param1=c1, param2=c2)
if not len(circles):
return None
return circles[0][0]
def detect_optic_disk(image_rgb, disk_center, out_name):
scale = 100
w_sum = cv2.addWeighted(image_rgb, 4, cv2.GaussianBlur(image_rgb, (0, 0), scale / 30), -4, 128)# * circular_mask + 128 * (1 - circular_mask)
# Image.fromarray(np.mean(w_sum, axis=2).astype(np.uint8)).save(out_name)
edges = canny(np.mean(w_sum, axis=2).astype(np.uint8), sigma=1.,
low_threshold=50.)#, high_threshold=100.)
result = hough_ellipse(edges, threshold=10, min_size=45, max_size=55)
result.sort(order='accumulator')
best = list(result[-1])
yc, xc, a, b = [int(round(x)) for x in best[1:5]]
orientation = best[5]
cy, cx = ellipse_perimeter(yc, xc, a, b, orientation)
image_rgb[cy, cx] = (0, 0, 255)
Image.fromarray(image_rgb).save(out_name)
def kaggle_BG(img, scale):
# Create a mask from which the approximate retinal center can be calculated
guide_mask = create_mask(img)
retina_center = tuple((np.mean(np.argwhere(guide_mask), axis=0)).astype(np.uint8))[::-1]
# Generate a circle of the approximate size, centered based on the guide mask
cf = 1.2
circular_mask = np.zeros(img.shape)
cv2.circle(circular_mask, retina_center, int(scale * cf), (1, 1, 1), -1, 8, 0)
# Compute weight sum of image, blurred image and mask it
w_sum = cv2.addWeighted(img, 4, cv2.GaussianBlur(img, (0, 0), scale / 30), -4, 128) * circular_mask + 128 * (1 - circular_mask)
return w_sum.astype(np.uint8)
# https://github.com/btgraham/SparseConvNet/blob/kaggle_Diabetic_Retinopathy_competition/Data/
# kaggleDiabeticRetinopathy/preprocessImages.py
def houghTransform(image, edges):
rho = 2
theta = np.pi/180
threshold = 15
min_line_length = 40
max_line_gap = 20
line_image = np.copy(image)*0 #creating a blank to draw lines on
# Run Hough on edge detected image
lines = cv2.HoughLinesP(edges, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
# Iterate over the output "lines" and draw lines on the blank
for line in lines:
for x1,y1,x2,y2 in line:
cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),10)
# Create a "color" binary image to combine with line image
color_edges = np.dstack((edges, edges, edges))
# Draw the lines on the edge image
combo = cv2.addWeighted(color_edges, 0.8, line_image, 1, 0)
return combo
def mark_point(img, x, y):
"""
Mark a point
Args:
- img(numpy): the source image
- x, y(int): position
"""
overlay = img.copy()
output = img.copy()
alpha = 0.5
radius = max(5, min(img.shape[:2])//15)
center = int(x), int(y)
color = (0, 0, 255)
cv2.circle(overlay, center, radius, color, -1)
cv2.addWeighted(overlay, alpha, output, 1-alpha, 0, output)
return output
project3.py 文件源码
项目:Self-Driving-Car-ND-Predict-Steering-Angle-with-CV
作者: sjamthe
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def yellowgrayscale(image):
#enhance yellow then find grayscale
#image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# define range of yellow color in HSV
#lower = np.array([40,40,40])
#upper = np.array([150,255,255])
#RGB limits
lower = np.array([80,80,40])
upper = np.array([255,255,80])
# Threshold the HSV image to get only yellow colors
mask = cv2.inRange(image, lower, upper)
#show_image('mask',mask)
# Bitwise-AND mask and original image
res = cv2.bitwise_and(image,image, mask= mask)
res = cv2.addWeighted(res, 1.0, image, 1.0, 0)
res = grayscale(res)
return res
project3.py 文件源码
项目:Self-Driving-Car-ND-Predict-Steering-Angle-with-CV
作者: sjamthe
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def weighted_img(img, initial_img, ?=0.8, ?=1., ?=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * ? + img * ? + ?
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, ?, img, ?, ?)
# In[8]:
def update_edge_mask(self, previous_mask, previous_line, slope_sign, thrs1, thrs2, debug):
lines = cv2.HoughLinesP(self.edge, 1, np.pi / 180, 70, minLineLength = 10, maxLineGap = 200)
lines = filter_lines(lines, self.vanishing_height, self.edge.shape[0], slope_sign)
self.lines.extend(lines)
mask = np.zeros(self.edge.shape, np.uint8)
for line in lines:
x1,y1,x2,y2 = line
cv2.line(mask, (x1,y1),(x2,y2), 255, MASK_WIDTH)
mask = cv2.addWeighted(mask, MASK_WEIGHT, previous_mask, 1 - MASK_WEIGHT, 0)
#self.current_mask *= int(255.0 / self.current_mask.max())
previous_mask = mask.copy()
_, mask = cv2.threshold(mask, 40, 255, cv2.THRESH_BINARY)
masked_edges = cv2.morphologyEx(cv2.bitwise_and(self.edge, self.edge, mask = mask), cv2.MORPH_CLOSE, np.array([[1] * EDGE_DILATION] *EDGE_DILATION))
lines2 = cv2.HoughLinesP(masked_edges, 1, np.pi / 180, 70, minLineLength = 10, maxLineGap = 200)
lines2 = filter_lines(lines2, self.vanishing_height, self.edge.shape[0], slope_sign)
self.lines2.extend(lines2)
for line in lines2:
x1,y1,x2,y2 = line
cv2.line(mask, (x1,y1),(x2,y2), 255, MASK_WIDTH)
previous_line[0] = add(previous_line[0], (x2,y2))
previous_line[1] = add(previous_line[1], (x_at_y(self.edge.shape[0]*0.6, x1, y1, x2, y2), self.edge.shape[0]*0.6))
previous_line[0] = scale(previous_line[0], 1.0 / (len(lines2) + 1))
previous_line[1] = scale(previous_line[1], 1.0 / (len(lines2) + 1))
return masked_edges, mask, previous_mask, previous_line
def highlightRois(image, roisCoords, roiWidthHeight):
rois = []
for roiCoord in roisCoords:
roiTopLeft = roiCoord['topLeft']
name = roiCoord['name']
# extract the regions of interest from the image
roiBottomRight = tuple([sum(x) for x in zip(roiTopLeft, roiWidthHeight)])
roi = image[roiTopLeft[1]:roiBottomRight[1], roiTopLeft[0]:roiBottomRight[0]]
rois.append({'topLeft': roiTopLeft, 'bottomRight': roiBottomRight, 'area': roi, 'name': name})
# construct a darkened transparent 'layer' to darken everything
# in the image except for the regions of interest
mask = np.zeros(image.shape, dtype = "uint8")
image = cv2.addWeighted(image, 0.25, mask, 0.75, 0)
# put the original rois back in the image so that they look 'brighter'
for roi in rois:
image[roi['topLeft'][1]:roi['bottomRight'][1], roi['topLeft'][0]:roi['bottomRight'][0]] = roi['area']
cv2.putText(image, roi['name'][0], roi['topLeft'], cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2)
return image
def gradient_img(colorsrc):
'''
http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/sobel_derivatives/sobel_derivatives.html
'''
SCALE = 1
DELTA = 0
DDEPTH = cv2.CV_16S ## to avoid overflow
graysrc = cv2.cvtColor(colorsrc, cv2.cv.CV_BGR2GRAY)
graysrc = cv2.GaussianBlur(graysrc, (3, 3), 0)
## gradient X ##
gradx = cv2.Sobel(graysrc, DDEPTH, 1, 0, ksize=3, scale=SCALE, delta=DELTA)
gradx = cv2.convertScaleAbs(gradx)
## gradient Y ##
grady = cv2.Sobel(graysrc, DDEPTH, 0, 1, ksize=3, scale=SCALE, delta=DELTA)
grady = cv2.convertScaleAbs(grady)
grad = cv2.addWeighted(gradx, 0.5, grady, 0.5, 0)
return grad
def animpingpong(self):
obj=self.Object
res=None
for t in obj.OutList:
print t.Label
img=t.ViewObject.Proxy.img.copy()
if res==None:
res=img.copy()
else:
#rr=cv2.subtract(res,img)
#rr=cv2.add(res,img)
aw=0.0+float(obj.aWeight)/100
bw=0.0+float(obj.bWeight)/100
print aw
print bw
if obj.aInverse:
# b umsetzen
ret, mask = cv2.threshold(img, 50, 255, cv2.THRESH_BINARY)
img=cv2.bitwise_not(mask)
rr=cv2.addWeighted(res,aw,img,bw,0)
res=rr
#b,g,r = cv2.split(res)
cv2.imshow(obj.Label,res)
#cv2.imshow(obj.Label +" b",b)
#cv2.imshow(obj.Label + " g",g)
#cv2.imshow(obj.Label + " r",r)
res=img
if not obj.matplotlib:
cv2.imshow(obj.Label,img)
else:
from matplotlib import pyplot as plt
# plt.subplot(121),
plt.imshow(img,cmap = 'gray')
plt.title(obj.Label), plt.xticks([]), plt.yticks([])
plt.show()
self.img=img
def weighted_img(img, initial_img, ?=0.8, ?=1., ?=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * ? + img * ? + ?
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, ?, img, ?, ?)
def _drawSpeed(image, speed, frameHeight=480, frameWidth=640):
maxBars = 8
numBars = min(int(speed/6)+1, maxBars) # 6 m/s per speed bar
for i in xrange(maxBars):
overlay = image.copy()
color = (10, 42*i, 42*(maxBars-1-i)) # BGR
cv2.rectangle(
overlay, (i*20, frameHeight-i*10),
(frameWidth-i*20, frameHeight-(i+1)*10), color, thickness=-1)
opacity = 0.08
cv2.addWeighted(overlay, opacity, image, 1-opacity, 0, image)
if i <= numBars:
# Shade bars to represent the speed
opacity = 0.4
cv2.addWeighted(overlay, opacity, image, 1-opacity, 0, image)
def _drawSpeed(image, speed, frameHeight=480, frameWidth=640):
maxBars = 8
numBars = min(int(speed/6)+1, maxBars) # 6 m/s per speed bar
for i in xrange(maxBars):
overlay = image.copy()
color = (10, 42*i, 42*(maxBars-1-i)) # BGR
cv2.rectangle(
overlay, (i*20, frameHeight-i*10),
(frameWidth-i*20, frameHeight-(i+1)*10), color, thickness=-1)
opacity = 0.08
cv2.addWeighted(overlay, opacity, image, 1-opacity, 0, image)
if i <= numBars:
# Shade bars to represent the speed
opacity = 0.4
cv2.addWeighted(overlay, opacity, image, 1-opacity, 0, image)
def overlay_mask(mask, image):
#make the mask rgb
rgb_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
#calculates the weightes sum of two arrays. in our case image arrays
#input, how much to weight each.
#optional depth value set to 0 no need
img = cv2.addWeighted(rgb_mask, 0.5, image, 0.5, 0)
return img
def road_lines(image):
""" Takes in a road image, re-sizes for the model,
predicts the lane to be drawn from the model in G color,
recreates an RGB image of a lane and merges with the
original road image.
"""
# Get image ready for feeding into model
small_img = imresize(image, (80, 160, 3))
small_img = np.array(small_img)
small_img = small_img[None,:,:,:]
# Make prediction with neural network (un-normalize value by multiplying by 255)
prediction = model.predict(small_img)[0] * 255
# Add lane prediction to list for averaging
lanes.recent_fit.append(prediction)
# Only using last five for average
if len(lanes.recent_fit) > 5:
lanes.recent_fit = lanes.recent_fit[1:]
# Calculate average detection
lanes.avg_fit = np.mean(np.array([i for i in lanes.recent_fit]), axis = 0)
# Generate fake R & B color dimensions, stack with G
blanks = np.zeros_like(lanes.avg_fit).astype(np.uint8)
lane_drawn = np.dstack((blanks, lanes.avg_fit, blanks))
# Re-size to match the original image
lane_image = imresize(lane_drawn, (720, 1280, 3))
# Merge the lane drawing onto the original image
result = cv2.addWeighted(image, 1, lane_image, 1, 0)
return result