def get(self): template = JINJA_ENVIRONMENT.get_template('templates/caredit/list.html') unknown = CarModel.all().filter('name =', 'Annet').fetch(5) assert len(unknown)==1 unknown_cars = Car.all().filter('model =', unknown[0]).fetch(50) other = CarModel.all().filter('name =', 'Annen Alfa Romeo').fetch(5) assert len(other)==1 other_cars = Car.all().filter('model =', other[0]).fetch(50) data = { 'cars': other_cars + unknown_cars, 'linker': LookupReg() } self.response.write(template.render(data))
def get(self): template = JINJA_ENVIRONMENT.get_template( 'templates/caredit/list.html') unknown = CarModel.all().filter('name =', 'Annet').fetch(5) assert len(unknown) == 1 unknown_cars = Car.all().filter('model =', unknown[0]).fetch(50) other = CarModel.all().filter('name =', 'Annen Alfa Romeo').fetch(5) assert len(other) == 1 other_cars = Car.all().filter('model =', other[0]).fetch(50) data = {'cars': other_cars + unknown_cars, 'linker': LookupReg()} self.response.write(template.render(data))
class Car(Model): name = CarModel() price = Price() placa = LicensePlate() def __repr__(self): return '<%s %s>' % (self.name, self.price)
def import_member_cars(self, csv): import traceback from utils.carconversion import MemberCar self.models = CarModel.all().fetch(2000) cars = [] lines = csv.split('\n') for line in lines: if len(line.strip()) == 0: continue fields = line.split(';') fields.reverse() car = MemberCar(memberno=fields.pop()) car.description = fields.pop().strip() car.registration = fields.pop().strip() year = fields.pop().strip() if year != '': car.year = int(year) else: car.year = 0 cars.append(car) print len(cars), 'cars imported' print len(self.models), 'models to use' try: print utils.carconversion.CarRank.do_matching( self.models, cars, self.create_member_car) except Exception as ex: print 'Exception matching car: ', ex print '*' * 80 traceback.print_exc() print '*' * 80
def import_member_cars(self, csv): import traceback from utils.carconversion import MemberCar self.models = CarModel.all().fetch(2000) cars = [] lines = csv.split('\n') for line in lines: if len(line.strip()) == 0: continue fields = line.split(';') fields.reverse() car = MemberCar(memberno=fields.pop()) car.description = fields.pop().strip() car.registration = fields.pop().strip() year = fields.pop().strip() if year != '': car.year = int(year) else: car.year = 0 cars.append(car) print len(cars), 'cars imported' print len(self.models), 'models to use' try: print utils.carconversion.CarRank.do_matching(self.models, cars, self.create_member_car) except Exception as ex: print 'Exception matching car: ',ex print '*'*80 traceback.print_exc() print '*'*80
def get(self, range_id, model_id): template = JINJA_ENVIRONMENT.get_template( 'templates/carmodels/model_detail.html') model_range = ModelRange.get(range_id) car_model = CarModel.get(model_id) data = {'range': model_range, 'model': car_model} self.response.write(template.render(data))
def get(self, range_id, model_id): template = JINJA_ENVIRONMENT.get_template('templates/carmodels/model_detail.html') model_range = ModelRange.get(range_id) car_model = CarModel.get(model_id) data = { 'range': model_range, 'model': car_model } self.response.write(template.render(data))
def __init__(self, **kwargs): """ Initialize the game object kwargs -- the keywords arguments are given to the carModel """ model = CarModel(**kwargs) view = CarView(model) behaviour = CarBehaviour('human', None, model) super(Car, self).__init__(gameObjectModel=model, gameObjectBehaviour=behaviour, gameObjectView=view) logging.log(1, "Trace: Car.__init__(%s)" % kwargs)
def post(self): import datetime car_key = self.request.get('car_key') model_key = self.request.get('model_key') car = Car.get(car_key) car.model = CarModel.get(model_key) car.notes = '' car.put() print 'Updated car model to', car.model.name ts = datetime.datetime.now() return self.redirect('/caredit?tag=' + str(ts.time().microsecond))
def post(self): import datetime car_key = self.request.get('car_key') model_key = self.request.get('model_key') car = Car.get(car_key) car.model = CarModel.get(model_key) car.notes = '' car.put() print 'Updated car model to',car.model.name ts = datetime.datetime.now() return self.redirect('/caredit?tag='+str(ts.time().microsecond))
def post(self, range_id, model_id): model_range = ModelRange.get(range_id) if self.request.get('cancel') == '1': return self.redirect('/ranges/' + str(model_range.key()) + '/edit') model = CarModel.get(model_id) model.name = self.request.get('name') model.year_from = int(self.request.get('yearfrom')) model.year_to = int(self.request.get('yearto')) model.typeno = self.request.get('tipo') model.engine_code = self.request.get('engine') url = self.request.get('image_url') if url != '': model.image_url = db.Link(url) model.notes = self.request.get('notes') model.put() return self.redirect('/ranges/' + str(model_range.key()) + '/edit')
def initialize(): wpod_net_path = "model/wpod-net.json" wpod_net = CarModel.load_model(wpod_net_path) # Load model architecture, weight and labels json_file = open('model/MobileNets_character_recognition.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) model.load_weights("model/License_character_recognition_weight.h5") print("[INFO] Model loaded successfully...") labels = LabelEncoder() labels.classes_ = np.load('model/license_character_classes.npy') print("[INFO] Labels loaded successfully...") return wpod_net, model, labels
def post(self, member_id, car_id): if self.request.get('cancel') == '1': return self.redirect('/members/' + member_id + '/edit') car = Car.get(car_id) car.registration = self.request.get('registration') yearstr = self.request.get('year') year = 0 if yearstr != '': year = int(self.request.get('year')) if year > 0: car.year = year else: car.year = None yearstr = self.request.get('bought') year = 0 if yearstr != '': year = int(self.request.get('bought')) if year > 0: car.bought_year = year else: car.bought_year = None yearstr = self.request.get('sold') year = 0 if yearstr != '': year = int(self.request.get('sold')) if year > 0: car.sold_year = year else: car.sold_year = None model_key = self.request.get('model_key') if not car.model or not str(car.model.key()) == model_key: car.model = CarModel.get(model_key) car.serial_no = self.request.get('serial_no') car.notes = self.request.get('note') car.put() return self.redirect('/members/' + member_id + '/edit')
from model import CarModel import matplotlib.pyplot as plt # Config n = 100 # Amount of model steps car_count = 20 # Amount of cars in model width = 100 # Road size acceleration = 1 speed_limit = 5 randomization = 0.05 vision_range = speed_limit * 3 all_speeds = [] all_tracked_agent_speeds = [] model = CarModel(car_count, width, acceleration, vision_range, randomization, speed_limit) for i in range(n): model.step() total = 0 tracked_agent_total = 0 for agent in model.schedule.agents: total += agent.speed if agent.unique_id == round(car_count / 2): tracked_agent_total += agent.speed all_speeds.append(total / model.num_agents) all_tracked_agent_speeds.append(tracked_agent_total) print('all_speeds:', all_speeds) plt.xlabel("Steps") plt.ylabel("Average speed")
def get_default_model(): """Return the default model name""" return CarModel.all().filter('name', DEFAULT_MODEL_NAME).fetch(1)[0]
def evaluting(wpod_net, model, labels, test_image_path="Plate_examples/mul2.jpg"): vehicle, LpImg,cor = CarHelpers.get_plate(test_image_path, wpod_net) if (len(LpImg)): #check if there is at least one license image # Scales, calculates absolute values, and converts the result to 8-bit. plate_image = cv2.convertScaleAbs(LpImg[0], alpha=(255.0)) # convert to grayscale and blur the image gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray,(7,7),0) # Applied inversed thresh_binary binary = cv2.threshold(blur, 140, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) thre_mor = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel3) # visualize results fig = plt.figure(figsize=(12,7)) plt.rcParams.update({"font.size":18}) grid = gridspec.GridSpec(ncols=2,nrows=3,figure = fig) plot_image = [plate_image, gray, blur, binary,thre_mor] plot_name = ["plate_image","gray","blur","binary","dilation"] for i in range(len(plot_image)): fig.add_subplot(grid[i]) plt.axis(False) plt.title(plot_name[i]) if i ==0: plt.imshow(plot_image[i]) else: plt.imshow(plot_image[i],cmap="gray") plt.savefig('img/plot_image.jpg', dpi=300) # Create sort_contours() function to grab the contour of each digit from left to right def sort_contours(cnts,reverse = False): i = 0 boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse)) return cnts cont, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # creat a copy version "test_roi" of plat_image to draw bounding box test_roi = plate_image.copy() # Initialize a list which will be used to append charater image crop_characters = [] # define standard width and height of character digit_w, digit_h = 30, 60 for c in sort_contours(cont): (x, y, w, h) = cv2.boundingRect(c) ratio = h/w if 1<=ratio<=6.5: # Only select contour with defined ratio if h/plate_image.shape[0]>=0.3: # Select contour which has the height larger than 50% of the plate # Draw bounding box arroung digit number cv2.rectangle(test_roi, (x, y), (x + w, y + h), (0, 255,0), 2) # Sperate number and give prediction curr_num = thre_mor[y:y+h,x:x+w] curr_num = cv2.resize(curr_num, dsize=(digit_w, digit_h)) _, curr_num = cv2.threshold(curr_num, 140, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # 220 - 225 crop_characters.append(curr_num) print("Detect {} letters...".format(len(crop_characters))) fig = plt.figure(figsize=(10,6)) plt.axis(False) plt.imshow(test_roi) plt.savefig('img/test_roi.jpg', dpi=300,bbox_inches='tight') #plt.savefig('grab_digit_contour.png',dpi=300) fig = plt.figure(figsize=(14,4)) grid = gridspec.GridSpec(ncols=len(crop_characters),nrows=1,figure=fig) for i in range(len(crop_characters)): fig.add_subplot(grid[i]) plt.axis(False) plt.imshow(crop_characters[i],cmap="gray") plt.savefig('img/crop_characters.jpg') #plt.savefig("segmented_leter.png",dpi=300,bbox_inches='tight') fig = plt.figure(figsize=(15,3)) cols = len(crop_characters) grid = gridspec.GridSpec(ncols=cols,nrows=1,figure=fig) final_string = '' for i,character in enumerate(crop_characters): fig.add_subplot(grid[i]) title = np.array2string(CarModel.predict_from_model(character,model,labels)) plt.title('{}'.format(title.strip("'[]"),fontsize=20)) final_string+=title.strip("'[]") plt.axis(False) plt.imshow(character,cmap='gray') plt.savefig('img/character.jpg', dpi=300,bbox_inches='tight') print(final_string) plt.savefig('img/final_result.jpg', dpi=300,bbox_inches='tight') return final_string
import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from local_utils import detect_lp from os.path import splitext,basename from keras.models import model_from_json from keras.preprocessing.image import load_img, img_to_array from keras.applications.mobilenet_v2 import preprocess_input from sklearn.preprocessing import LabelEncoder import glob from model import CarModel from helpers import CarHelpers wpod_net_path = "model/wpod-net.json" wpod_net = CarModel.load_model(wpod_net_path) test_image_path = "Plate_examples/2.jpg" vehicle, LpImg,cor = CarHelpers.get_plate(test_image_path, wpod_net) fig = plt.figure(figsize=(12,6)) grid = gridspec.GridSpec(ncols=2,nrows=1,figure=fig) fig.add_subplot(grid[0]) plt.axis(False) plt.imshow(vehicle) grid = gridspec.GridSpec(ncols=2,nrows=1,figure=fig) fig.add_subplot(grid[1]) plt.axis(False) plt.imshow(LpImg[0]) if (len(LpImg)): #check if there is at least one license image
def import_car_models(self, csv): ranges = ModelRange.all().fetch(100) imported = 0 lines = csv.split('\n') for line in lines: if len(line.strip()) == 0: print 'Skipping line',line continue model = CarModel() fields = line.strip().split(';') model.model_range = self.get_range(ranges, fields[0].strip()) model.name = fields[1].strip() model.engine_code = fields[2].strip() model.typeno = fields[3].strip() if fields[4].strip() != '': model.image_url = db.Link(fields[4].strip()) model.year_from = int(fields[5]) model.year_to = int(fields[6]) model.notes = fields[7].strip() model.put() imported = imported + 1 print imported,'models imported'
def import_car_models(self, csv): ranges = ModelRange.all().fetch(100) imported = 0 lines = csv.split('\n') for line in lines: if len(line.strip()) == 0: print 'Skipping line', line continue model = CarModel() fields = line.strip().split(';') model.model_range = self.get_range(ranges, fields[0].strip()) model.name = fields[1].strip() model.engine_code = fields[2].strip() model.typeno = fields[3].strip() if fields[4].strip() != '': model.image_url = db.Link(fields[4].strip()) model.year_from = int(fields[5]) model.year_to = int(fields[6]) model.notes = fields[7].strip() model.put() imported = imported + 1 print imported, 'models imported'
def task_model_restore(items): model_count = 0 for item in items: mrange = ModelRange() mrange.name = item['name'] mrange.year_start = item['yearStart'] mrange.year_end = item['yearEnd'] mrange.notes = item['notes'] mrange.put() for model in item['carModels']: carmodel = CarModel(key_name=model['modelId']) carmodel.name = model['name'] carmodel.engine_code = model['engineCode'] carmodel.typeno = model['typeNo'] if model['imageUrl'] != None: carmodel.imageUrl = db.Link(model['imageUrl']) carmodel.year_from = model['yearFrom'] carmodel.year_to = model['yearTo'] carmodel.notes = model['notes'] carmodel.model_range = mrange carmodel.put() model_count = model_count + 1
results_delay = [] for num, cars in enumerate(traffic_occupations, start=0): print("Running: " + str(cars) + " cars..") results_speed.append([]) results_delay.append([]) settings = [] for x in speed_limits: settings.append([cars, 100, acceleration, 50, randomization, x]) for num_setting, setting in enumerate(settings, start=0): results_speed[num].append([]) results_delay[num].append([]) all_delay = [] all_speeds = [] model = CarModel(*setting) for i in range(n): model.step() # Store the results total = 0 for agent in model.schedule.agents: total += agent.speed ave_speed = total / model.num_agents all_delay.append(abs(setting[5] - ave_speed)) all_speeds.append(ave_speed) results_speed[num][num_setting] = np.mean(all_speeds) results_delay[num][num_setting] = np.mean(all_delay) def plot_line(x_data, y_data, y_label):