def show_results(self, set_number, seq_number, frame_number, clas_guess, guess_pos, guess_scores, original_image=False): self.load_annotations() # Will be needed if CaltechDataset.USE_CROPPING: if original_image: image = Image.open( self.dataset_location + '/images/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) else: image = Image.open( self.dataset_location + '/images-cropped/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) transform = np.load( self.dataset_location + '/images-cropped/set{:02d}/V{:03d}.seq/{}.transform.npy'. format(set_number, seq_number, frame_number)) else: image = Image.open(self.dataset_location + '/images/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) dr = ImageDraw.Draw(image) # Retrieve objects for that frame in annotations try: objects = self.annotations['set{:02d}'.format(set_number)][ 'V{:03d}'.format(seq_number)]['frames']['{}'.format( frame_number)] except KeyError as e: objects = None # Simply no objects for that frame if objects: for o in objects: pos = (o['pos'][1], o['pos'][0], o['pos'][3], o['pos'][2] ) # Convert to (y, x, h, w) if CaltechDataset.USE_CROPPING and not original_image: pos = transform_cropped_pos(pos, transform) if o['lbl'] in ['person']: good = True # Remove objects with very small width (are they errors in labeling?!) if pos[3] < CaltechDataset.MINIMUM_WIDTH: good = False if o['occl'] == 1: if type(o['posv']) == int: good = False else: visible_pos = (o['posv'][1], o['posv'][0], o['posv'][3], o['posv'][2] ) # Convert to (y, x, h, w) if CaltechDataset.USE_CROPPING and not original_image: visible_pos = transform_cropped_pos( visible_pos, transform) if visible_pos[2] * visible_pos[ 3] < CaltechDataset.MINIMUM_VISIBLE_RATIO * pos[ 2] * pos[3]: good = False pos = visible_pos if good: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='blue') else: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='pink') else: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='black') if not CaltechDataset.USE_CROPPING or not original_image: for y in range(clas_guess.shape[0]): for x in range(clas_guess.shape[1]): for anchor_id in range(clas_guess.shape[2]): if clas_guess[y, x, anchor_id] == 0.0: # Negative dr.rectangle( (CaltechDataset.OUTPUT_CELL_SIZE * x, CaltechDataset.OUTPUT_CELL_SIZE * y, CaltechDataset.OUTPUT_CELL_SIZE * (x + 1) - 1, CaltechDataset.OUTPUT_CELL_SIZE * (y + 1) - 1), outline='red') else: # Positive dr.rectangle( (CaltechDataset.OUTPUT_CELL_SIZE * x, CaltechDataset.OUTPUT_CELL_SIZE * y, CaltechDataset.OUTPUT_CELL_SIZE * (x + 1) - 1, CaltechDataset.OUTPUT_CELL_SIZE * (y + 1) - 1), outline='green') for row in range(guess_pos.shape[0]): pos = guess_pos[row] if CaltechDataset.USE_CROPPING and original_image: pos = untransform_cropped_pos(pos, transform) dr.rectangle((pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='green') dr.text((pos[1], pos[0]), '{:.3f}'.format(guess_scores[row])) image.show()
def binary_classificn_pts(extent=0, datt=[], scale=1, r=np.eye(2), t1=0, t2=0, trnsp1=120, trnsp2=120, trp1_hi=120, trp1_lo=120, trp2_hi=120, trp2_lo=120, hi1_ind=1000, lo1_ind=0, hi2_ind=1000, lo2_ind=0, xshift1=0, xshift2=0): # Basic stuff with points. w=5 im = Image.new("RGB", (2048, 2048), (1, 1, 1)) draw = ImageDraw.Draw(im, 'RGBA') if extent == 0: return (im, draw) means1_orig = np.array([500, 1500]) means2_orig = np.array([1500, 500]) means1 = generalized_planar_rotation(means1_orig, np.array([1000,1000]), r) means2 = generalized_planar_rotation(means2_orig, np.array([1000,1000]), r) p=0.3 center_1_orig = means1_orig*p+means2_orig*(1-p) center_2_orig = means2_orig*p+means1_orig*(1-p) center_1 = means1*p+means2*(1-p) center_2 = means2*p+means1*(1-p) means = center_1 stds = [300, 300] corr = 0.8 # correlation covs = [[stds[0]**2 , stds[0]*stds[1]*corr], [stds[0]*stds[1]*corr, stds[1]**2]] np.random.seed(0) m_1 = np.random.multivariate_normal(center_1_orig, covs, 200)*scale m = m_1 for i in range(m.shape[0]): r_pt = generalized_planar_rotation(m[i], np.array([1000,1000]), r) if extent > 0 and extent < 5: draw.ellipse((r_pt[0]-w,r_pt[1]-w,r_pt[0]+w,r_pt[1]+w), fill = (255,30,102), outline = (0,0,0)) means = center_2 np.random.seed(4) m_2 = np.random.multivariate_normal(center_2_orig, covs, 200)*scale m = m_2 for i in range(m.shape[0]): r_pt = generalized_planar_rotation(m[i], np.array([1000,1000]), r) if extent > 1 and extent < 5: draw.ellipse((r_pt[0]-w,r_pt[1]-w,r_pt[0]+w,r_pt[1]+w), fill = (20,255,102), outline = (0,0,0)) # Draw the separating line. center = (center_1+center_2)/2 orthog = -np.dot(planar_rotation(-np.pi/2), (center_2-center_1)) main_dircn = (center_2 - center_1) p=2.0 pt_1 = center + orthog*p pt_2 = center - orthog*p if extent > 2: draw.line((pt_1[0], pt_1[1], pt_2[0], pt_2[1]), fill = 'grey', width = 7) avgs = [] means = np.sum(m_1,axis=1)/2 avgs2 = [] means2 = np.sum(m_2,axis=1)/2 for i in range(len(means)): avgs.append((((m_1[i][1]<m_1[i][0]))-0.5)*2*np.sqrt(sum((m_1[i]-means[i])**2))) avgs2.append((((m_2[i][1]<m_2[i][0]))-0.5)*2*np.sqrt(sum((m_2[i]-means2[i])**2))) avgs = np.array(avgs) avgs2 = np.array(avgs2) dat1 = m_1[avgs > np.percentile(avgs,97)] dat2 = m_2[avgs2 < np.percentile(avgs,4)] for i in dat1: datt.append(i) for i in dat2: datt.append(i) xs = [1000] for i in range(1,8): pt_1_a = pt_1 + main_dircn*i/7 pt_1_b = pt_1 - main_dircn*i/7 pt_2_a = pt_2 + main_dircn*i/7 pt_2_b = pt_2 - main_dircn*i/7 if extent > 3: draw.line((pt_1_a[0], pt_1_a[1], pt_2_a[0], pt_2_a[1]), fill = (255,255,255,100), width = 4) draw.line((pt_1_b[0], pt_1_b[1], pt_2_b[0], pt_2_b[1]), fill = (255,255,255,100), width = 4) xs.append(pt_1_a[0]) xs.append(pt_1_b[0]) xs.sort() xs.append(max(xs)+xs[1]-xs[0]) xs.append(min(xs)-xs[1]+xs[0]) # I basically want to transfer the last element to the first position # so sort is overkill. But it's a small array, so no matter. xs.sort() if extent > 4: drip_to_bins(draw, xs, m, t1, r, rgb=(20,255,102), transparency=trnsp1, trp_hi=trp1_hi, trp_lo=trp1_lo, hi_ind=hi1_ind,lo_ind=lo1_ind,xshift=xshift1) drip_to_bins(draw, xs, m_1, t2, r, rgb=(255,20,102), transparency=trnsp2, trp_hi=trp2_hi, trp_lo=trp2_lo, hi_ind=hi2_ind,lo_ind=lo2_ind,xshift=xshift2) return (im, draw)
def show_custom_labels(model, photo, min_confidence): rekognition = boto3.client('rekognition') # # Load image from S3 bucket # s3_connection = boto3.resource('s3') # # s3_object = s3_connection.Object(bucket, photo) # s3_response = s3_object.get() # # stream = io.BytesIO(s3_response['Body'].read()) # read in photo image = cv2.imread(photo) # if has frame then resize and encode it as jpg hasFrame, imageBytes = cv2.imencode(".jpg", image) # run image against model response = rekognition.detect_custom_labels(Image={ 'Bytes': imageBytes.tobytes(), }, ProjectVersionArn=model, MinConfidence=min_confidence) #convert from cv2 to PIL image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) imgWidth, imgHeight = image_pil.size draw = ImageDraw.Draw(image_pil) # calculate and display bounding boxes for each detected custom label print('Detected custom labels for ' + photo) for customLabel in response['CustomLabels']: print('Label ' + str(customLabel['Name'])) print('Confidence ' + str(customLabel['Confidence'])) if 'Geometry' in customLabel: box = customLabel['Geometry']['BoundingBox'] left = imgWidth * box['Left'] top = imgHeight * box['Top'] width = imgWidth * box['Width'] height = imgHeight * box['Height'] x = left + (width / 2) y = top - (height / 2) fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 50) draw.text((left, top), customLabel['Name'], fill='#00d400', font=fnt) print('Left: ' + '{0:.0f}'.format(left)) print('Top: ' + '{0:.0f}'.format(top)) print('Label Width: ' + "{0:.0f}".format(width)) print('Label Height: ' + "{0:.0f}".format(height)) print('X: {}, Y: {}'.format(x, y)) points = ((left, top), (left + width, top), (left + width, top + height), (left, top + height), (left, top)) draw.line(points, fill='#00d400', width=5) image_pil.show() return len(response['CustomLabels'])
#print(ud) #print(kn_fac_encodis) count=0 for check in kn_fac_encodis: #print("Check",check) # Load an image with an unknown face unknown_image = face_recognition.load_image_file("E:\\Face Detection\\DEMO 3\\image\\tamizhh.jpg") #am , sugu, suu , unknownface, tamizhh, # Find all the faces and face encodings in the unknown image face_locations = face_recognition.face_locations(unknown_image) #face_locations = face_recognition.face_locations(image, model="cnn") #face_encodings = face_recognition.face_encodings(unknown_image, face_locations) # Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library # See http://pillow.readthedocs.io/ for more about PIL/Pillow pil_image = Image.fromarray(unknown_image) # Create a Pillow ImageDraw Draw instance to draw with draw = ImageDraw.Draw(pil_image) #dupl=[] locations, face_encodings = get_face_embeddings_from_image(unknown_image) #print("Encoding_Face_embedding",face_encodings[0]) #print("Encoding_Face_encoding",face_encodings) matches = face_recognition.compare_faces(check, face_encodings[0]) face_distances = face_recognition.face_distance(check, face_encodings[0]) print(face_distances) if face_distances[0]<0.44: print("Photo Matched.....!!!") count=count+1 #print(di[str(check)]) names.append(di[str(check)]) else: print("Not Matched..!")
def test(): import torchvision transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.485,0.456,0.406), (0.229,0.224,0.225)) ]) dataType = 'train2017' root_path = "../COCO_dataset/images/%s"%(dataType) list_root_path = "./data/%s.txt"%(dataType) dataset = ListDataset(root=root_path,list_file=list_root_path, train=True, transform=transform, input_size=360) dataloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=1, collate_fn=dataset.collate_fn) for images, loc_targets, cls_targets in dataloader: print(images.shape) print(loc_targets.shape) print(cls_targets.shape) grid = torchvision.utils.make_grid(images, 1) torchvision.utils.save_image(grid, 'a.jpg') print('Loading image..') net = RetinaNet() net.eval() img = Image.open('a.jpg') w = h = 360 img = img.resize((w,h)) print('Predicting..') x = transform(img) x = x.unsqueeze(0) x = Variable(x) use_cuda = torch.cuda.is_available() device = torch.device("cuda" if use_cuda else "cpu") print('Device used:', device) if torch.cuda.is_available(): net = net.to(device) x = x.to(device) loc_targets = loc_targets.to(device) with torch.no_grad(): loc_preds, cls_preds = net(x) print(loc_preds.shape) print(cls_preds.shape) print('Decoding..') encoder = DataEncoder() boxes, labels, _ = encoder.decode(loc_targets.data.cpu()[0], cls_preds.data.cpu().squeeze(), (w,h)) print("Label : ",labels) draw = ImageDraw.Draw(img) # use a truetype font font = ImageFont.truetype("./font/DELIA_regular.ttf", 20) for i,(box,label) in enumerate(zip(boxes,labels)): draw.rectangle(list(box), outline=color_map(int(label)),width = 5) draw.rectangle(list([box[0],box[1]-17,box[0]+10*len(my_cate[int(label)])+5,box[1]]), outline=color_map(int(label)),width = 3,fill=color_map(int(label))) draw.text((box[0]+3, box[1]-16), my_cate[int(label)],font = font,fill = (0, 0, 0, 100),width = 5) plt.imshow(img) plt.savefig("./test.jpg") break
def detectar_emociones(foto): data = open(foto, 'rb') #headers = {'Ocp-Apim-Subscription-Key': KEY} Se puede usar este header cuando usa un url de internet y en lugar de data usa json{url: url(entre comillas)} headers = { 'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY } #Funciona porque tiene el content type params = { 'returnFaceAttributes': 'emotion', } face_api_url = BASE_URL + 'detect' response = requests.post(face_api_url, params=params, headers=headers, data=data) json_detected = response.json() face_ids = [d['faceId'] for d in json_detected] identified_faces = CF.face.identify(face_ids, PERSON_GROUP_ID) for identified in identified_faces: candidates_list = identified['candidates'] print("Candidates", candidates_list) if candidates_list != []: candidates = candidates_list[0] persona = candidates['personId'] persona_info = CF.person.get(PERSON_GROUP_ID, persona) person_name = persona_info['name'] emociones = {} for resp in json_detected: if resp['faceId'] == identified['faceId']: faceRectangle = resp['faceRectangle'] width = faceRectangle['width'] top = faceRectangle['top'] height = faceRectangle['height'] left = faceRectangle['left'] emociones = resp['faceAttributes']['emotion'] print("EMOCIONES", emociones) break image = Image.open(foto) draw = ImageDraw.Draw(image) draw.rectangle((left, top, left + width, top + height), outline='red') font = ImageFont.truetype('Roboto-Regular.ttf', 20) draw.text((0, 0), person_name, font=font, fill="black") #emociones = detectar_emociones(foto) y = 20 font_emotion = ImageFont.truetype('Roboto-Regular.ttf', 15) for e in emociones: if emociones[e] > 0.0: emocion = traducir_sentimiento(e) draw.text((10, y), emocion, font=font_emotion, fill="black") draw.text((70, y), str(round(emociones[e] * 100, 2)) + "%", font=font_emotion, fill="black") y += 20 image.show() return '''for j in json_detected:
# left, top, right, bottom = 1100, 870, 1700, 1700 # cropped = imageObject.crop((left, top, right, bottom)) # # # Display the cropped portion # # cropped.show() # cropped_image.save(saved_location) path = '/Users/jordanwalker/Downloads/lance-modis-sa/' filelist = glob.glob(os.path.join(path, '*.jpg')) filenames = sorted(x for x in filelist) for im in filenames: saved_location = im.replace('lance-modis-sa', 'lance-modis-sa-name') im_object = im.split('/') img_split = im_object[-1].split('.') file_label = img_split[-3] imageObject = Image.open(im) draw = ImageDraw.Draw(imageObject) font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 16) draw.text((5, 5), file_label[0:4], (255, 255, 255), font=font) imageObject.save(saved_location) # If you need to crop # left, top, right, bottom = 1100, 870, 1700, 1700 # cropped = imageObject.crop((left, top, right, bottom)) # cropped.save(saved_location)
async def seasoncreate(self, data, seasondata, season, profile, seasonname): font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf" bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf" name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8") header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8") operator = random.choice(self.bgs) bg_image = Image.open( f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA") profile_image = Image profile_avatar = BytesIO() profile_url = data.avatar_url_256 async with self.session.get(profile_url) as r: profile_img = await r.content.read() profile_avatar = BytesIO(profile_img) profile_image = Image.open(profile_avatar).convert("RGBA") # set canvas bg_color = (255, 255, 255, 0) result = Image.new("RGBA", (1600, 1080), bg_color) process = Image.new("RGBA", (1600, 1080), bg_color) # draw draw = ImageDraw.Draw(process) # puts in background bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS) bg_image = bg_image.crop((0, 0, 1920, 1080)) result.paste(bg_image, (0, 0)) aviholder = self.add_corners( Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10) process.paste(aviholder, (1295, 15), aviholder) process.paste(profile_image, (1300, 20)) # op badge if season >= 14: ranks = self.ranksember else: ranks = self.ranks url = self.rankurl + ranks[seasondata["rank_text"]] process.paste(aviholder, (995, 15), aviholder) im = Image.open(BytesIO(await self.getimg(url))) im = im.resize((256, 256), Image.ANTIALIAS) process.paste(im, (1000, 20)) # data # draw.text((440, 40), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt) draw.text( ( self._center( 440, 1000, "Name: {}".format(self._truncate_text(data.username, 18)), header_fnt, ), 40, ), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( ( self._center(440, 1000, "Platform: {}".format( str(data.platform).title()), header_fnt), 90, ), "Platform: {}".format(str(data.platform).title()), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( ( self._center( 440, 1000, "Region: {}".format( self.regions[seasondata["region"]]), header_fnt), 140, ), "Region: {}".format(self.regions[seasondata["region"]]), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (self._center(440, 1000, f"{seasonname} Statistics", header_fnt), 190), f"{seasonname} Statistics", fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (520, 320), "Games Played: {}".format(seasondata["wins"] + seasondata["losses"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 380), "Wins: {}".format(seasondata["wins"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (960, 380), "Losses: {}".format(seasondata["losses"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 440), "Abandons: {}".format(seasondata["abandons"]), fill=(255, 255, 255, 255), font=name_fnt, ) try: wlr = round( seasondata["wins"] / (seasondata["wins"] + seasondata["losses"]), 2) except ZeroDivisionError: wlr = 0 draw.text( (960, 440), "Total W/LR: {}%".format(wlr * 100), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 520), "Kills: {}".format(seasondata["kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (960, 520), "Deaths: {}".format(seasondata["deaths"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 580), "MMR: {}".format(seasondata["mmr"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 640), "Max MMR: {}".format(seasondata["max_mmr"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 700), "Previous Rank MMR: {}".format(seasondata["prev_rank_mmr"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 760), "Next Rank MMR: {}".format(seasondata["next_rank_mmr"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 820), "Rank: {}".format(seasondata["rank_text"]), fill=(255, 255, 255, 255), font=name_fnt, ) if seasondata["rank_text"] == "Champions": draw.text( (960, 820), "Champion Rank Position: {}".format( seasondata["champions_rank_position"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 880), "Max Rank: {}".format(seasondata["max_rank_text"]), fill=(255, 255, 255, 255), font=name_fnt, ) result = Image.alpha_composite(result, process) file = BytesIO() result.save(file, "png") file.name = f"season-{data.username}.png" file.seek(0) image = discord.File(file) return image
async def profilecreate(self, data): font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf" bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf" name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8") header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8") operator = random.choice(self.bgs) bg_image = Image.open( f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA") profile_image = Image profile_avatar = BytesIO() profile_url = data.avatar_url_256 async with self.session.get(profile_url) as r: profile_img = await r.content.read() profile_avatar = BytesIO(profile_img) profile_image = Image.open(profile_avatar).convert("RGBA") # set canvas bg_color = (255, 255, 255, 0) result = Image.new("RGBA", (1280, 1080), bg_color) process = Image.new("RGBA", (1280, 1080), bg_color) # draw draw = ImageDraw.Draw(process) # puts in background bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS) bg_image = bg_image.crop((0, 0, 1920, 1080)) result.paste(bg_image, (0, 0)) aviholder = self.add_corners( Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10) process.paste(aviholder, (995, 15), aviholder) process.paste(profile_image, (1000, 20)) # data draw.text( ( self._center( 440, 1000, "Name: {}".format(self._truncate_text(data.username, 18)), header_fnt, ), 40, ), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( ( self._center(440, 1000, "Platform: {}".format( str(data.platform).title()), header_fnt), 90, ), "Platform: {}".format(str(data.platform).title()), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (self._center(440, 1000, "General Statistics", header_fnt), 140), "General Statistics", fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (self._center(1000, 1256, f"Level: {data.level}", header_fnt), 300), f"Level: {data.level}", fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (520, 400), "Wins: {}".format(data.general_stats["wins"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 400), "Losses: {}".format(data.general_stats["losses"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 470), "Draws: {}".format(data.general_stats["draws"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 470), "Total W/LR: {}%".format( round( data.general_stats["wins"] / data.general_stats["games_played"], 2) * 100), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 540), "Lootbox %: {}%".format(data.lootbox_probability), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 610), "Kills: {}".format(data.general_stats["kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 610), "Deaths: {}".format(data.general_stats["deaths"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 680), "Assists: {}".format(data.general_stats["assists"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 680), "KDR: {}".format(data.general_stats["kd"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 750), "Revives: {}".format(data.general_stats["revives"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 750), "Suicides: {}".format(data.general_stats["suicides"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 820), "Blind Kills: {}".format(data.general_stats["blind_kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 820), "Melee Kills: {}".format(data.general_stats["melee_kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 890), "Pentration Kills: {}".format( data.general_stats["penetration_kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 890), "DBNOs: {}".format(data.general_stats["dbnos"]), fill=(255, 255, 255, 255), font=name_fnt, ) m, _ = divmod(data.general_stats["playtime"], 60) h, m = divmod(m, 60) d, h = divmod(h, 24) draw.text( (520, 1010), f"Playtime: {d:d}d {h:d}h {m:02d}m", fill=(255, 255, 255, 255), font=name_fnt, ) result = Image.alpha_composite(result, process) file = BytesIO() result.save(file, "png") file.name = f"general-{data.username}.png" file.seek(0) image = discord.File(file) return image
def plotBBoxes(image, bboxes, classes=None, scores=None, color='Chartreuse', linewidth=2, use_rgb=False): """Plot bounding boxes for given input objects Arguments: ---------- image : numpy.array input image for drawing bboxes : list((x1, y1, x2, y2)) input bounding boxes of objects to draw Keyword Arguments: ------------------ classes : list(str) (default: None) list of classes for objects color : str (default: `Chartreuse`) color to plot linewidth : int (default: 2) how thick the shape is use_rgb : bool (default: False) whether using RGB image or not (apply for NDArray image) Returns: -------- image : numpy.array output image after drawing """ if len(bboxes) == 0: return image exit() if isinstance(image, np.ndarray): if not use_rgb: image = cv.cvtColor(image, cv.COLOR_BGR2RGB) image = Image.fromarray(image) W, H = image.size draw = ImageDraw.Draw(image) if classes is not None: font = ImageFont.truetype(font=cfg.FONT, size=np.floor(3e-2 * min(H, W) + 0.5).astype('int32')) for i, ((x1, y1, x2, y2), cls) in enumerate(zip(bboxes, classes)): # draw bounding box draw.rectangle([x1, y1, x2, y2], outline=ImageColor.getrgb(COLOR_MAP[cls]), width=linewidth) # draw label text = cls if scores is not None: text = '{} {:.2f}'.format(cls, scores[i]) label_size = draw.textsize(text, font) text_coor = np.array( [x1 + linewidth, max(0, y1 - label_size[1] - 1)]) rec_coor = np.array([x1, text_coor[1]]) draw.rectangle([ tuple(rec_coor), tuple(rec_coor + label_size + np.array([linewidth * 2, 0])) ], fill=ImageColor.getrgb(COLOR_MAP[cls])) draw.text(text_coor, text, fill=ImageColor.getrgb('black'), font=font) else: for i, (x1, y1, x2, y2) in enumerate(bboxes): draw.rectangle([x1, y1, x2, y2], outline=ImageColor.getrgb(color), width=linewidth) del draw return image
async def casualstatscreate(self, data): font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf" bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf" name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8") header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8") operator = random.choice(self.bgs) bg_image = Image.open( f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA") profile_image = Image profile_avatar = BytesIO() profile_url = data.avatar_url_256 async with self.session.get(profile_url) as r: profile_img = await r.content.read() profile_avatar = BytesIO(profile_img) profile_image = Image.open(profile_avatar).convert("RGBA") # set canvas bg_color = (255, 255, 255, 0) result = Image.new("RGBA", (1280, 1080), bg_color) process = Image.new("RGBA", (1280, 1080), bg_color) # draw draw = ImageDraw.Draw(process) # puts in background bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS) bg_image = bg_image.crop((0, 0, 1920, 1080)) result.paste(bg_image, (0, 0)) aviholder = self.add_corners( Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10) process.paste(aviholder, (995, 15), aviholder) process.paste(profile_image, (1000, 20)) # data # draw.text((440, 40), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt) draw.text( ( self._center( 440, 1000, "Name: {}".format(self._truncate_text(data.username, 18)), header_fnt, ), 40, ), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( ( self._center(440, 1000, "Platform: {}".format( str(data.platform).title()), header_fnt), 90, ), "Platform: {}".format(str(data.platform).title()), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (self._center(440, 1000, "Alltime Ranked Statistics", header_fnt), 140), "Alltime Casual Statistics", fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (self._center(1000, 1256, f"Level: {data.level}", header_fnt), 300), f"Level: {data.level}", fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (520, 400), "Games Played: {}".format( data.queue_stats["casual"]["games_played"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 480), "Wins: {}".format(data.queue_stats["casual"]["wins"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 480), "Losses: {}".format(data.queue_stats["casual"]["losses"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 560), "Draws: {}".format(data.queue_stats["casual"]["draws"]), fill=(255, 255, 255, 255), font=name_fnt, ) try: wlr = (round( data.queue_stats["casual"]["wins"] / data.queue_stats["casual"]["games_played"], 2, ) * 100) except ZeroDivisionError: wlr = 0 draw.text((520, 640), "Total W/LR: {}%".format(wlr), fill=(255, 255, 255, 255), font=name_fnt) draw.text( (520, 800), "Kills: {}".format(data.queue_stats["casual"]["kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 800), "Deaths: {}".format(data.queue_stats["casual"]["deaths"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 880), "KDR: {}".format(data.queue_stats["casual"]["kd"]), fill=(255, 255, 255, 255), font=name_fnt, ) m, _ = divmod(data.queue_stats["casual"]["playtime"], 60) h, m = divmod(m, 60) d, h = divmod(h, 24) draw.text( (520, 960), f"Playtime: {d:d}d {h:d}h {m:02d}m", fill=(255, 255, 255, 255), font=name_fnt, ) result = Image.alpha_composite(result, process) file = BytesIO() result.save(file, "png") file.name = f"casual-{data.username}.png" file.seek(0) image = discord.File(file) return image
def create_validate_code(size=(120, 30), chars=chars, mode="RGB", \ bg_color=(255, 255, 255), fg_color=(255, 0, 0), \ font_size=18, font_type="msyh.ttf", \ length=4, draw_points=True, point_chance = 2): ''' size: 图片的大小,格式(宽,高),默认为(120, 30) chars: 允许的字符集合,格式字符串 mode: 图片模式,默认为RGB bg_color: 背景颜色,默认为白色 fg_color: 前景色,验证码字符颜色 font_size: 验证码字体大小 font_type: 验证码字体,需要指定一个字体文件的路径 length: 验证码字符个数 draw_points: 是否画干扰点 point_chance: 干扰点出现的概率,大小范围[0, 50] ''' width, height = size img = Image.new(mode, size, bg_color) draw = ImageDraw.Draw(img) '''随机取出指定个数符串''' get_chars = lambda : random.sample(chars, length) def create_points(): '''绘制干扰点,遍历这个图片的所有点,根据概率决定时候加黑点点''' chance = min(50, max(0, int(point_chance))) # 大小限制在[0, 50] for w in xrange(width): for h in xrange(height): tmp = random.randint(0, 50) if tmp > 50 - chance: draw.point((w, h), fill=(0, 0, 0)) def create_strs(): '''绘制验证码字符,验证码的主体''' c_chars = get_chars() strs = '%s' % ''.join(c_chars) font = ImageFont.truetype(font_type, font_size) font_width, font_height = font.getsize(strs) #起码的一组参数是位置 draw.text(((width - font_width) / 3, (height - font_height) / 4), strs, font=font, fill=fg_color) return strs if draw_points: create_points() strs = create_strs() #图形扭曲参数 params = [1 - float(random.randint(1, 2)) / 100, 0, 0, 0, 1 - float(random.randint(1, 10)) / 100, float(random.randint(1, 2)) / 500, 0.001, float(random.randint(1, 2)) / 500 ] img = img.transform(size, Image.PERSPECTIVE, params) # 创建扭曲 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大) print strs img.save("code1.jpg", "JPEG", quality=85)
def update_frame(self, frame): img = Image.fromarray(frame) draw = ImageDraw.Draw(img) # draw rectangle around the 5 first detected object with a score greater # than 60% if self.result_scores[0][0] > 0.60: y0 = int(self.get_object_location_y0(0) * frame.shape[0]) x0 = int(self.get_object_location_x0(0) * frame.shape[1]) y1 = int(self.get_object_location_y1(0) * frame.shape[0]) x1 = int(self.get_object_location_x1(0) * frame.shape[1]) label = self.get_label(0) accuracy = self.result_scores[0][0] * 100 draw.rectangle([(x0, y0), (x1, y1)], outline=(0, 0, 255)) draw.rectangle([(x0, y0), (x0 + ((len(label) + 4) * char_text_width), y0 + 14)], (0, 0, 255)) draw.text((x0 + 2, y0 + 2), label + " " + str(int(accuracy)) + "%", (255, 255, 255)) if self.result_scores[0][1] > 0.60: y0 = int(self.get_object_location_y0(1) * frame.shape[0]) x0 = int(self.get_object_location_x0(1) * frame.shape[1]) y1 = int(self.get_object_location_y1(1) * frame.shape[0]) x1 = int(self.get_object_location_x1(1) * frame.shape[1]) label = self.get_label(1) accuracy = self.result_scores[0][1] * 100 draw.rectangle([(x0, y0), (x1, y1)], outline=(255, 0, 0)) draw.rectangle([(x0, y0), (x0 + ((len(label) + 4) * char_text_width), y0 + 14)], (255, 0, 0)) draw.text((x0 + 2, y0 + 2), label + " " + str(int(accuracy)) + "%", (255, 255, 255)) if self.result_scores[0][2] > 0.60: y0 = int(self.get_object_location_y0(2) * frame.shape[0]) x0 = int(self.get_object_location_x0(2) * frame.shape[1]) y1 = int(self.get_object_location_y1(2) * frame.shape[0]) x1 = int(self.get_object_location_x1(2) * frame.shape[1]) label = self.get_label(2) accuracy = self.result_scores[0][2] * 100 draw.rectangle([(x0, y0), (x1, y1)], outline=(0, 255, 0)) draw.rectangle([(x0, y0), (x0 + ((len(label) + 4) * char_text_width), y0 + 14)], (0, 255, 0)) draw.text((x0 + 2, y0 + 2), label + " " + str(int(accuracy)) + "%", (255, 255, 255)) if self.result_scores[0][3] > 0.60: y0 = int(self.get_object_location_y0(3) * frame.shape[0]) x0 = int(self.get_object_location_x0(3) * frame.shape[1]) y1 = int(self.get_object_location_y1(3) * frame.shape[0]) x1 = int(self.get_object_location_x1(3) * frame.shape[1]) label = self.get_label(3) accuracy = self.result_scores[0][3] * 100 draw.rectangle([(x0, y0), (x1, y1)], outline=(255, 255, 0)) draw.rectangle([(x0, y0), (x0 + ((len(label) + 4) * char_text_width), y0 + 14)], (255, 255, 0)) draw.text((x0 + 2, y0 + 2), label + " " + str(int(accuracy)) + "%", (255, 255, 255)) if self.result_scores[0][4] > 0.60: y0 = int(self.get_object_location_y0(4) * frame.shape[0]) x0 = int(self.get_object_location_x0(4) * frame.shape[1]) y1 = int(self.get_object_location_y1(4) * frame.shape[0]) x1 = int(self.get_object_location_x1(4) * frame.shape[1]) label = self.get_label(4) accuracy = self.result_scores[0][4] * 100 draw.rectangle([(x0, y0), (x1, y1)], outline=(0, 255, 255)) draw.rectangle([(x0, y0), (x0 + ((len(label) + 4) * char_text_width), y0 + 14)], (0, 255, 255)) draw.text((x0 + 2, y0 + 2), label + " " + str(int(accuracy)) + "%", (255, 255, 255)) data = img.tobytes() data = GLib.Bytes.new(data) pixbuf = GdkPixbuf.Pixbuf.new_from_bytes( data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.shape[2] * frame.shape[1]) self.image.set_from_pixbuf(pixbuf.copy())
def compute_matches(self, set_number, seq_number, frame_number, guess_pos, guess_scores, original_image=False, display_image=False): self.load_annotations() # Will be needed if CaltechDataset.USE_CROPPING: if display_image: if original_image: image = Image.open( self.dataset_location + '/images/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) else: image = Image.open( self.dataset_location + '/images-cropped/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) transform = np.load( self.dataset_location + '/images-cropped/set{:02d}/V{:03d}.seq/{}.transform.npy'. format(set_number, seq_number, frame_number)) elif display_image: image = Image.open(self.dataset_location + '/images/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) if display_image: dr = ImageDraw.Draw(image) # Retrieve objects for that frame in annotations try: objects = self.annotations['set{:02d}'.format(set_number)][ 'V{:03d}'.format(seq_number)]['frames']['{}'.format( frame_number)] except KeyError as e: objects = None # Simply no objects for that frame # We attempt to mimic the reasonable test set # i.e. 50 pixels or taller, no occlusion (not even partial) persons = [] undesirables = [] if objects: for o in objects: good = False pos = (o['pos'][1], o['pos'][0], o['pos'][3], o['pos'][2] ) # Convert to (y, x, h, w) if CaltechDataset.USE_CROPPING and not original_image: pos = transform_cropped_pos(pos, transform) if o['lbl'] in ['person']: good = True # 50 pixels or taller if pos[2] < 50: good = False if o['occl'] == 1: good = False if good: persons.append(pos) if display_image: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='blue') else: undesirables.append(pos) if display_image: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='pink') # Move data to numpy persons = np.array(persons, dtype=np.float32) undesirables = np.array(undesirables, dtype=np.float32) # Sort guesses index = np.argsort( guess_scores[:])[::-1] # Decreasing order with [::-1] guess_pos = guess_pos[index] guess_scores = guess_scores[index] default_false_positives = 0 guess_matched = np.zeros(guess_scores.shape, dtype=np.bool) for row in range(guess_pos.shape[0]): pos = guess_pos[row] if CaltechDataset.USE_CROPPING and original_image: pos = untransform_cropped_pos(pos, transform) # Try matching matched = False if persons.shape[0] > 0: for r in range(persons.shape[0]): if IoU(pos, persons[r]) > 0.5: matched = True persons = np.delete(persons, r, 0) break if matched: guess_matched[row] = True if display_image: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='green') else: if undesirables.shape[0] > 0: for r in range(undesirables.shape[0]): if IoA(pos, undesirables[r]) > 0.5: matched = True break if not matched: default_false_positives += 1 if display_image: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='red') elif display_image: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='yellow') if display_image: dr.text((pos[1], pos[0]), '{:.3f}'.format(guess_scores[row])) # Sorted scores of all matches made for computing curves matched_scores = guess_scores[guess_matched] default = np.array([default_false_positives, persons.shape[0]]) if display_image: image.show() return matched_scores, default
def interface(): #Initialisation pygame.init() base, label, distance_matrix = init() #Création de la fenêtre window = pygame.display.set_mode((560, 340), pygame.RESIZABLE) #chargement et application de la zone de dessin et des boutons draw = pygame.image.load("vide.png").convert() validate = pygame.image.load("valider.png").convert() cancel = pygame.image.load("annuler.png").convert() b0 = pygame.image.load("0.png").convert() b1 = pygame.image.load("1.png").convert() b2 = pygame.image.load("2.png").convert() b3 = pygame.image.load("3.png").convert() b4 = pygame.image.load("4.png").convert() b5 = pygame.image.load("5.png").convert() b6 = pygame.image.load("6.png").convert() b7 = pygame.image.load("7.png").convert() b8 = pygame.image.load("8.png").convert() b9 = pygame.image.load("9.png").convert() blearn = pygame.image.load("?.png").convert() black = pygame.image.load("noir.png").convert() bRM = pygame.image.load("ADD.png").convert() window.blit(draw, (10, 10)) window.blit(cancel, (120, 10)) window.blit(validate, (230, 10)) window.blit(bRM, (450, 10)) window.blit(b0, (10, 120)) window.blit(b1, (120, 120)) window.blit(b2, (230, 120)) window.blit(b3, (340, 120)) window.blit(b4, (450, 120)) window.blit(b5, (10, 230)) window.blit(b6, (120, 230)) window.blit(b7, (230, 230)) window.blit(b8, (340, 230)) window.blit(b9, (450, 230)) #création de l'image destination et mise en blanc picture = Image.new("RGB", (100, 100)) initPicture(picture) draw_img = ImageDraw.Draw(picture) #Raffraichissement de la fenêtre pygame.display.flip() learn = 0 continuer = 1 # saving the last px used for smoothing last_x = 0 last_y = 0 while continuer: for event in pygame.event.get(): #gestion de la fermeture de la fenêtre if event.type == QUIT: close(base, label, distance_matrix) continuer = 0 pygame.quit() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 11 and event.pos[0] < 109 and \ event.pos[1] > 11 and event.pos[1] < 109 : last_x = event.pos[0] last_y = event.pos[1] #gestion du dessin if event.type == MOUSEMOTION and event.buttons[0] == 1 and \ event.pos[0] > 11 and event.pos[0] < 109 and \ event.pos[1] > 11 and event.pos[1] < 109 : learn = 1 new_x = event.pos[0] new_y = event.pos[1] window.blit(black, (340, 10)) draw_img.line( (last_x - 10, last_y - 10, new_x - 10, new_y - 10), fill='black', width=5) last_x = new_x last_y = new_y #drawPixel(picture,event.pos[0]-10,event.pos[1]-10) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) pygame.display.flip() #gestion du boulon annuler if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 121 and event.pos[0] < 219 and \ event.pos[1] > 11 and event.pos[1] < 109 : learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() #gestion du bouton RM if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 451 and event.pos[0] < 549 and \ event.pos[1] > 11 and event.pos[1] < 109 : learn = 1 window.blit(blearn, (340, 10)) pygame.display.flip() #gestion du bouton valider if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 231 and event.pos[0] < 329 and \ event.pos[1] > 11 and event.pos[1] < 109 and learn == 1 : picture.save("new.png") #ouverture du fichier source new_picture = Image.open("new.png") word = picture2word(new_picture) digit = analyse.analyse_triangle_knn_multi( word, base, label, distance_matrix, 3) word2 = None if (zoomout("new.png", "new2.png")): new_picture2 = Image.open("new2.png") word2 = picture2word(new_picture2) digit2 = analyse.analyse_triangle_knn_multi( word2, base, label, distance_matrix, 3) if digit == 0: window.blit(b0, (340, 10)) elif digit == 1: window.blit(b1, (340, 10)) elif digit == 2: window.blit(b2, (340, 10)) elif digit == 3: window.blit(b3, (340, 10)) elif digit == 4: window.blit(b4, (340, 10)) elif digit == 5: window.blit(b5, (340, 10)) elif digit == 6: window.blit(b6, (340, 10)) elif digit == 7: window.blit(b7, (340, 10)) elif digit == 8: window.blit(b8, (340, 10)) elif digit == 9: window.blit(b9, (340, 10)) else: window.blit(blearn, (340, 10)) # if digit != -1 : # learn = 2 # base[digit].append(word) # if learn == 1 : # window.blit(blearn, (340,10)) # else : # initPicture(picture) # picture.save("temp.png") # draw = pygame.image.load("temp.png").convert() # window.blit(draw, (10,10)) pygame.display.flip() #gestion des boutons chiffres if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 11 and event.pos[0] < 109 and \ event.pos[1] > 121 and event.pos[1] < 219 and learn == 1 : base.append(word) label.append(0) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(0) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 121 and event.pos[0] < 219 and \ event.pos[1] > 121 and event.pos[1] < 219 and learn == 1 : base.append(word) label.append(1) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(1) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 231 and event.pos[0] < 329 and \ event.pos[1] > 121 and event.pos[1] < 219 and learn == 1 : base.append(word) label.append(2) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(2) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 341 and event.pos[0] < 439 and \ event.pos[1] > 121 and event.pos[1] < 219 and learn == 1: base.append(word) label.append(3) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(3) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 451 and event.pos[0] < 549 and \ event.pos[1] > 121 and event.pos[1] < 219 and learn == 1 : base.append(word) label.append(4) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(4) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 11 and event.pos[0] < 109 and \ event.pos[1] > 231 and event.pos[1] < 329 and learn == 1 : base.append(word) label.append(5) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(5) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 121 and event.pos[0] < 219 and \ event.pos[1] > 231 and event.pos[1] < 329 and learn == 1 : base.append(word) label.append(6) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(6) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 231 and event.pos[0] < 329 and \ event.pos[1] > 231 and event.pos[1] < 329 and learn == 1 : base.append(word) label.append(7) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(7) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 341 and event.pos[0] < 439 and \ event.pos[1] > 231 and event.pos[1] < 329 and learn == 1 : base.append(word) label.append(8) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(8) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip() if event.type == MOUSEBUTTONDOWN and event.button == 1 and \ event.pos[0] > 451 and event.pos[0] < 549 and \ event.pos[1] > 231 and event.pos[1] < 329 and learn == 1 : base.append(word) label.append(9) distance_matrix = update_matrix(base, distance_matrix, word) if (word2 != None): base.append(word2) label.append(9) distance_matrix = update_matrix(base, distance_matrix, word2) learn = 0 initPicture(picture) picture.save("temp.png") draw = pygame.image.load("temp.png").convert() window.blit(draw, (10, 10)) window.blit(black, (340, 10)) pygame.display.flip()
async def operatorstatscreate(self, data, index, profile): font_file = f"{bundled_data_path(self)}/fonts/RobotoRegular.ttf" bold_file = f"{bundled_data_path(self)}/fonts/RobotoBold.ttf" name_fnt = ImageFont.truetype(font_file, 42, encoding="utf-8") header_fnt = ImageFont.truetype(bold_file, 42, encoding="utf-8") operator = random.choice(self.bgs) opdata = data.operators[index] bg_image = Image.open( f"{bundled_data_path(self)}/bg/{operator}.jpg").convert("RGBA") profile_image = Image profile_avatar = BytesIO() profile_url = data.avatar_url_256 async with self.session.get(profile_url) as r: profile_img = await r.content.read() profile_avatar = BytesIO(profile_img) profile_image = Image.open(profile_avatar).convert("RGBA") # set canvas bg_color = (255, 255, 255, 0) result = Image.new("RGBA", (1600, 1080), bg_color) process = Image.new("RGBA", (1600, 1080), bg_color) # draw draw = ImageDraw.Draw(process) # puts in background bg_image = bg_image.resize((1920, 1090), Image.ANTIALIAS) bg_image = bg_image.crop((0, 0, 1920, 1080)) result.paste(bg_image, (0, 0)) aviholder = self.add_corners( Image.new("RGBA", (266, 266), (255, 255, 255, 255)), 10) process.paste(aviholder, (1295, 15), aviholder) process.paste(profile_image, (1300, 20)) # op badge url = opdata["badge_image"] process.paste(aviholder, (995, 15), aviholder) im = Image.open(BytesIO(await self.getimg(url))) im = im.resize((256, 256), Image.ANTIALIAS) process.paste(im, (1000, 20)) # data # draw.text((440, 40), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt) draw.text( ( self._center( 440, 1000, "Name: {}".format(self._truncate_text(data.username, 18)), header_fnt, ), 40, ), "Name: {}".format(self._truncate_text(data.username, 18)), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( ( self._center(440, 1000, "Platform: {}".format( str(data.platform).title()), header_fnt), 90, ), "Platform: {}".format(str(data.platform).title()), fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (self._center(440, 1000, f"{opdata['name']} Statistics", header_fnt), 140), f"{opdata['name']} Statistics", fill=(255, 255, 255, 255), font=header_fnt, ) draw.text( (520, 320), "Games Played: {}".format(opdata["wins"] + opdata["losses"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text((520, 380), "Wins: {}".format(opdata["wins"]), fill=(255, 255, 255, 255), font=name_fnt) draw.text( (920, 380), "Losses: {}".format(opdata["losses"]), fill=(255, 255, 255, 255), font=name_fnt, ) try: wlr = round(opdata["wins"] / (opdata["wins"] + opdata["losses"]), 2) except ZeroDivisionError: wlr = 0 draw.text( (520, 440), "Total W/LR: {}%".format(wlr * 100), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (520, 520), "Kills: {}".format(opdata["kills"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text( (920, 520), "Deaths: {}".format(opdata["deaths"]), fill=(255, 255, 255, 255), font=name_fnt, ) draw.text((520, 580), "KDR: {}".format(opdata["kd"]), fill=(255, 255, 255, 255), font=name_fnt) draw.text( (520, 640), "Headshots: {}".format(opdata["headshots"]), fill=(255, 255, 255, 255), font=name_fnt, ) y = 760 for ability in opdata["abilities"]: draw.text( (520, y), "{}: {}".format(ability["ability"], ability["value"]), fill=(255, 255, 255, 255), font=name_fnt, ) y += 80 m, _ = divmod(opdata["playtime"], 60) h, m = divmod(m, 60) d, h = divmod(h, 24) draw.text( (520, 700), f"Playtime: {d:d}d {h:d}h {m:02d}m", fill=(255, 255, 255, 255), font=name_fnt, ) result = Image.alpha_composite(result, process) result = result.crop((500, 0, 1600, 1080)) file = BytesIO() result.save(file, "png") file.name = f"operator-{data.username}.png" file.seek(0) image = discord.File(file) return image
# http://www.pythonchallenge.com/pc/hex/copper.html # Page source says 'or maybe white.gif would be more bright' from PIL import Image, ImageDraw # white.gif downloaded from http://www.pythonchallenge.com/pc/hex/white.gif # white.gif is almost all black, with 1 pixel with (8, 8, 8) # Only 1 pixel has different color # The pixel is moving in the white.gif # Need to emulate the joystick img = Image.open('./resource/white.gif') # Variable to store new image new = Image.new('RGB', (500, 200)) draw = ImageDraw.Draw(new) # Set first point to start at the edge of image cx, cy = 0, 100 # Read all frames in white.gif for frame in range(img.n_frames): # Get frame img.seek(frame) # getbbox() get black box boundary left, upper, right, lower = img.getbbox() # Calculates the position of the non-black pixel # Set movement direction accordingly dx = left - 100 dy = upper - 100 # If black pixel is reset to original position # Move cursor 50 pixels to the right for more space if dx == dy == 0:
def round_corner(self, radius): """Draw a round corner""" corner = Image.new("L", (radius, radius), 0) draw = ImageDraw.Draw(corner) draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=255) return corner
def show_image_analysis(image_path, analysis): import matplotlib.pyplot as plt from PIL import Image, ImageDraw import numpy as np # Display the image fig = plt.figure(figsize=(16, 8)) a = fig.add_subplot(1, 2, 1) img = Image.open(image_path) # Get the caption caption_text = '' if (len(analysis.description.captions) == 0): caption_text = 'No caption detected' else: for caption in analysis.description.captions: caption_text = caption_text + " '{}'\n(Confidence: {:.2f}%)".format( caption.text, caption.confidence * 100) plt.title(caption_text) # Get objects if analysis.objects: # Draw a rectangle around each object for object in analysis.objects: r = object.rectangle bounding_box = ((r.x, r.y), (r.x + r.w, r.y + r.h)) draw = ImageDraw.Draw(img) draw.rectangle(bounding_box, outline='magenta', width=5) plt.annotate(object.object_property, (r.x, r.y), backgroundcolor='magenta') # Get faces if analysis.faces: # Draw a rectangle around each face for face in analysis.faces: r = face.face_rectangle bounding_box = ((r.left, r.top), (r.left + r.width, r.top + r.height)) draw = ImageDraw.Draw(img) draw.rectangle(bounding_box, outline='lightgreen', width=5) annotation = 'Person aged approxilately {}'.format(face.age) plt.annotate(annotation, (r.left, r.top), backgroundcolor='lightgreen') plt.axis('off') plt.imshow(img) # Add a second plot for addition details a = fig.add_subplot(1, 2, 2) # Get ratings ratings = 'Ratings:\n - Adult: {}\n - Racy: {}\n - Gore: {}'.format( analysis.adult.is_adult_content, analysis.adult.is_racy_content, analysis.adult.is_gory_content, ) # Get tags tags = 'Tags:' for tag in analysis.tags: tags = tags + '\n - {}'.format(tag.name) # Print details details = '{}\n\n{}'.format(ratings, tags) a.text(0, 0.4, details, fontsize=12) plt.axis('off') plt.show()
def draw_status_pie(status_totals: Counter, avatar_fp: Optional[BytesIO], *, show_totals: bool = True) -> BytesIO: image, draw = base_image() # Make pie max size if no totals if not show_totals: pie_size = IMAGE_SIZE pie_offset = (0,) * 2 else: pie_size = int(IMAGE_SIZE * 0.66) pie_offset = (0, (IMAGE_SIZE - pie_size) // 2) # Draw status pie pie_0 = add((0,) * 2, pie_offset) pie_1 = add((pie_size,) * 2, pie_offset) degrees = 270.0 for status, percentage in status_totals.most_common(): start = degrees degrees += 360 * percentage draw.pieslice((pie_0, pie_1), start, degrees, fill=COLOURS[status]) if avatar_fp is not None: # Load avatar image avatar = Image.open(avatar_fp) if avatar.mode != 'RGBA': avatar = avatar.convert('RGBA') avatar = avatar.resize((int(pie_size // 1.5),) * 2, resample=Image.LANCZOS) # Apply circular mask to image _, _, _, alpha = avatar.split() if alpha.mode != 'L': alpha = alpha.convert('L') mask = Image.new('L', avatar.size, 0) draw = ImageDraw.Draw(mask) draw.ellipse((0, 0) + avatar.size, fill=255) mask = ImageChops.darker(mask, alpha) avatar.putalpha(mask) # Overlay avatar image.paste(avatar, add((pie_size // 6,) * 2, pie_offset), avatar) # Add status percentages if show_totals: draw = ImageDraw.Draw(image) font = ImageFont.truetype('res/roboto-bold.ttf', IMAGE_SIZE // 20) x_offset = IMAGE_SIZE // 4 * 3 y_offset = IMAGE_SIZE // 3 circle_size = (IMAGE_SIZE // 30,) * 2 for status, percentage in status_totals.most_common(): offset = (x_offset, y_offset) draw.ellipse(offset + add(offset, circle_size), fill=COLOURS[status]) draw.text((x_offset + IMAGE_SIZE // 20, y_offset - IMAGE_SIZE // 60), f'{percentage:.2%}', font=font, align='left', fill=WHITE) y_offset += IMAGE_SIZE // 8 return as_bytes(resample(image))
from PIL import Image, ImageDraw # Image size (pixels) WIDTH = 36000 HEIGHT = 24000 # Plot window RE_START = -2 RE_END = 1 IM_START = -1 IM_END = 1 palette = [] im = Image.new('RGB', (WIDTH, HEIGHT), (0, 0, 0)) draw = ImageDraw.Draw(im) im = Image.new('RGB', (WIDTH, HEIGHT), (0, 0, 0)) draw = ImageDraw.Draw(im) for x in range(0, WIDTH): for y in range(0, HEIGHT): # Convert pixel coordinate to complex number c = complex(RE_START + (x / WIDTH) * (RE_END - RE_START), IM_START + (y / HEIGHT) * (IM_END - IM_START)) # Compute the number of iterations m = mandelbrot(c) # The color depends on the number of iterations color = 255 - int(m * 255 / MAX_ITER) # Plot the point draw.point([x, y], (color, color, color))
def draw_status_log(status_log: List[LogEntry], *, timezone: datetime.timezone = datetime.timezone.utc, show_labels: bool = False, num_days: int = 30) -> BytesIO: row_count = 1 + num_days + show_labels image, draw = base_image(IMAGE_SIZE * row_count, 1) # Set consts day_width = IMAGE_SIZE / (60 * 60 * 24) day_height = IMAGE_SIZE // row_count now = datetime.datetime.now(timezone) time_offset = now.utcoffset().total_seconds() # type: ignore total_duration = 0.0 if show_labels: time_offset += 60 * 60 * 24 # Draw status log entries for status, _, timespan in status_log: duration: float = timespan.total_seconds() total_duration += duration new_time_offset = time_offset + duration start_x = round(time_offset * day_width) end_x = round(new_time_offset * day_width) draw.rectangle(((start_x, 0), (end_x, 1)), fill=COLOURS[status]) time_offset = new_time_offset # Reshape Image pixels = numpy.array(image) # pixels = pixels[:, IMAGE_SIZE:] pixels = pixels.reshape(row_count, IMAGE_SIZE, 4) pixels = pixels.repeat(day_height, 0) image = Image.fromarray(pixels, 'RGBA') if show_labels: overlay = Image.new('RGBA', image.size, (0, 0, 0, 0)) draw = ImageDraw.Draw(overlay) # Set offsets based on font size font = ImageFont.truetype('res/roboto-bold.ttf', IMAGE_SIZE // int(1.66 * num_days)) text_width, text_height = draw.textsize('\N{FULL BLOCK}' * 2, font=font) height_offset = (day_height - text_height) // 2 x_offset = text_width y_offset = day_height # Add date labels date = now - datetime.timedelta(seconds=total_duration) for _ in range(int(total_duration // ONE_DAY) + 2): # 2 because of timezone offset woes # if weekend draw signifier if date.weekday() == 5: draw.rectangle((0, y_offset, IMAGE_SIZE, y_offset + (2 * day_height)), fill=TRANSLUCENT) # Add date _, text_height = draw.textsize(date.strftime('%b. %d'), font=font) draw.text((x_offset, y_offset + height_offset), date.strftime('%b. %d'), font=font, align='left', fill=WHITE) y_offset += day_height date += datetime.timedelta(days=1) # Add timezone label draw.text((x_offset, height_offset), str(timezone), font=font, align='left', fill='WHITE') # Add hour lines for i in range(1, 24): x_offset = ONE_HOUR * i colour = WHITE if not i % 6 else OPAQUE draw.line((x_offset, day_height, x_offset, IMAGE_SIZE), fill=colour, width=DOWNSAMPLE * 4) image = Image.alpha_composite(image, overlay) draw = ImageDraw.Draw(image) # Add time labels time = start_of_day(now) for x_offset in (ONE_HOUR * 6, ONE_HOUR * 12, ONE_HOUR * 18): time += datetime.timedelta(hours=6) text_width, _ = draw.textsize(time.strftime('%H:00'), font=font) draw.text((x_offset - (text_width // 2), height_offset), time.strftime('%H:00'), font=font, align='left', fill=WHITE) return as_bytes(resample(image))
def SavePILText(strAPODFileName): #use isfile logic to only create new ones, True to recreate them all if not os.path.isfile(strAPODPicsWithText + strAPODFileName): #True: print "Building Image With Text" #strAPODDataFolder + strAPODFileName.replace('.jpg', '_Info.txt') strInfo = "" strTitle = "" strContents = "" #if strAPODFileName == "ison_encke_hi1_srem_a.jpg": # print "stop here" #if strAPODFileName == "pileus_lowenstein_4320.jpg": # print "stop here" try: with open( strAPODDataFolder + strAPODFileName.replace('.jpg', '_Info.txt'), 'r') as content_file: strInfo = content_file.read() except Exception as e: print str(e) try: with open( strAPODDataFolder + strAPODFileName.replace('.jpg', '_Title.txt'), 'r') as content_file: strTitle = content_file.read() except Exception as e: print str(e) if strTitle.strip() <> "": strContents = strTitle.strip() if strInfo.strip() <> "": if strContents <> "": strContents = strContents + ': ' + strInfo.strip() else: strContents = strInfo.strip() else: strContents = strInfo.strip() try: TEXTCOLOR = (0, 0, 0) IMGCOLOR = (0, 0, 0, 255) OPCOLOR = (150, 150, 150, 255) X = 10 Y = 3 fontsize = 24 #how to I manage this on linux? font = ImageFont.truetype('arial.ttf', fontsize) im = PILImage.new( 'RGBA', (1920, 1080), IMGCOLOR) # PILImage.open('G:\\blank.png') #.convert('RGB') imgWidth, imgHeight = im.size draw = ImageDraw.Draw(im) sngHeight = imgHeight * 1.0 sngWidth = imgWidth * 1.0 bImageToTop = True #INSERT THE ORIGINAL INTO THE CANVAS strSource = strAPODPicturesFolder + strAPODFileName if os.path.isfile(strSource): imIN = PILImage.open(strSource) imgWidthIN, imgHeightIN = imIN.size if strAPODPicsVLF <> "": #print "checking for very large image" #convert very large images on the Pi down to QHD # if dimentions larger than 3840×2160 scale down to that size first sngWidthQHD = 3840.0 sngHeightQHD = 2160.0 if imgWidthIN > sngWidthQHD or imgHeightIN > sngHeightQHD: #convert titan5km_huygens_big.jpg -resize 3840x2160 test.jpg #subprocess.call(["ls", "-l"]) print "converting VLF" #strArgs = " '" + + "'" #print "convert " + strArgs #call(["ls", "-l"]) call([ "convert", strAPODPicturesFolder + strAPODFileName, "-resize", "3840x2160", strAPODPicsVLF + strAPODFileName ]) print "reopening VLF" imIN = PILImage.open(strAPODPicsVLF + strAPODFileName) imgWidthIN, imgHeightIN = imIN.size bResized = False if imgHeightIN > sngHeight: bResized = True sngChange = sngHeight / imgHeightIN imgHeightIN = int(sngHeight) imgWidthIN = int(imgWidthIN * sngChange) if imgWidthIN > sngWidth: bResized = True sngChange = sngWidth / imgWidthIN imgWidthIN = int(sngWidth) imgHeightIN = int(imgHeightIN * sngChange) szNew = imgWidthIN, imgHeightIN if bResized: imIN = imIN.resize(szNew, PILImage.ANTIALIAS) #does image go to right or to top? if ((imgWidthIN * 1.0) / imgHeightIN) > ( (imgWidth * 1.0) / imgHeight): #print "Input Image More Landscape - print to top" if imgHeightIN < (1080 / 2): offset = ((imgWidth - imgWidthIN) / 2, (1080 / 2) - imgHeightIN ) #(imgHeight-imgHeightIN)/2) else: offset = ((imgWidth - imgWidthIN) / 2, 0 ) #(imgHeight-imgHeightIN)/2) im.paste(imIN, offset) else: bImageToTop = False #print "Input Image More Portrait - print to right" offset = (min((1920 / 2), (imgWidth - imgWidthIN)), (imgHeight - imgHeightIN) / 2) im.paste(imIN, offset) #MANAGE THE TEXT OVERLAY #decide what gets printed on what line tmpLine = "" strLine = "" #print "Splitting Contents:" + strContents words = strContents.split(' ') #list of lines to print strLines = [] bLines = False if bImageToTop == True: #print "printing image to top, text underneath" for word in words: #print "10" if strLine == "": #print "20" strLine = word else: #print "30" strLine = strLine + ' ' + word #print "35" strLine = strLine.strip() #print "40: " + strLine if strLine <> "": #print "45" intWidth, intHeight = draw.textsize(strLine, font=font) #print "50" #print 'Text Render Width = ' + str(intWidth) + ', Text Render Height = ' + str(intHeight) if intWidth > (imgWidth - 20): #print "Drawing Text loop: " + tmpLine #draw.text((X, Y), tmpLine, font=font, fill=TEXTCOLOR) strLines.append(tmpLine) #print "100 %s, %s", X, Y #Y += 33 # intHeight * 1.1 #print "110" strLine = word tmpLine = strLine else: tmpLine = strLine #print "Drawing Text" #print "tmpLine = " + tmpLine if not tmpLine == "": #draw.text((X, Y), tmpLine, font=font, fill=TEXTCOLOR) strLines.append(tmpLine) else: print "Nothing To Print" if True: #False: #Print On The Opacity Layer behind the text #print "making opacity background" intLineEstimate = len(strLines) intRectHeight = intLineEstimate * 33 # 250 # calced by length of text intGradHeight = 40 sngGradVal = 0 intGradMaxOpacity = 210 intX = 1920 intY = 1080 bgimg = PILImage.new('RGBA', (intX, intY), OPCOLOR) gradient = PILImage.new('L', (1, intY)) for y in range(intY): if (y < (intY - (intRectHeight + intGradHeight))): gradient.putpixel((0, y), 0) elif (y < (intY - intRectHeight)): gradient.putpixel((0, y), int(sngGradVal)) sngGradVal = sngGradVal + ( (intGradMaxOpacity * 1.0) / intGradHeight) else: gradient.putpixel((0, y), intGradMaxOpacity) # resize the gradient to the size of im... alpha = gradient.resize(bgimg.size) # put alpha in the alpha band of im... bgimg.putalpha(alpha) #draw bgimg onto im im.paste(bgimg, (0, 0), bgimg) #print on the text bLines = False Y = (imgHeight - 10) - (len(strLines) * 33) for strLine in strLines: if strLine <> "": bLines = True draw.text((X, Y), strLine, font=font, fill=TEXTCOLOR) Y += 33 #print strLine else: intMaxDesiredLineWidth = max( 20, min((1920 / 2), (1920 - imgWidthIN)) - (X * 2)) - 10 #print "print image right, text to the left" if True: #print "new logic" intMaxLines = 32 intLinesUsed = 33 intTotalWidth, intTotalHeight = draw.textsize(strContents, font=font) while intLinesUsed > intMaxLines: #print "logic here" #run draw logic to find number of current lines intMaxDesiredLineWidth += 5 strLines[:] = [] #with PILImage.new('RGBA',(1920, 1080), IMGCOLOR) as imT: if True: imT = PILImage.new('RGBA', (1920, 1080), IMGCOLOR) imgWidthT, imgHeightT = imT.size drawT = ImageDraw.Draw(imT) for word in words: if strLine == "": strLine = word else: strLine = strLine + ' ' + word strLine = strLine.strip() if strLine <> "": intWidth, intHeight = drawT.textsize( strLine, font=font) if intWidth > (intMaxDesiredLineWidth - (X * 2)): strLines.append(tmpLine) strLine = word tmpLine = strLine else: tmpLine = strLine if not tmpLine == "": strLines.append(tmpLine) else: print "Nothing To Print" intLinesUsed = len(strLines) strLine = "" tmpLine = "" else: print "old logic" intTotalWidth, intTotalHeight = draw.textsize(strContents, font=font) intTotalPossibleLines = int(1080 / 33.0) - 3 intMaxDesiredLineWidth = max( 30, min((1920 / 2), (1920 - imgWidthIN)) - (X * 2)) intCurrentLines = intTotalWidth / (intMaxDesiredLineWidth - 10) intCurrentLines = (intTotalWidth * 1.15) / (intMaxDesiredLineWidth) #print "TotalPossibleLines: " + str(intTotalPossibleLines) #print "TotalWidth: " + str(intTotalWidth) #guess width per line # if lines * maxdesiredlinewidth > inttotalwidth make maxdesiredlinewidth longer while (intCurrentLines > intTotalPossibleLines) and ( intMaxDesiredLineWidth < 1920): #print "recalc intMaxDesiredLineWidth" intMaxDesiredLineWidth += 10 #intCurrentLines = (intTotalWidth * 1.1) / (intMaxDesiredLineWidth) # - ((X * 2) + 30)) intCurrentLines = (intTotalWidth * 1.15) / ( intMaxDesiredLineWidth) # - 10) if len(strLines) == intMaxLines: print "stop here" strLines[:] = [] for word in words: #print "10" if strLine == "": #print "20" strLine = word else: #print "30" strLine = strLine + ' ' + word #print "35" strLine = strLine.strip() #print "40: " + strLine if strLine <> "": #print "45" intWidth, intHeight = draw.textsize(strLine, font=font) #print "50" #print 'Text Render Width = ' + str(intWidth) + ', Text Render Height = ' + str(intHeight) if intWidth > (intMaxDesiredLineWidth - (X * 2)): #print "Drawing Text loop: " + tmpLine #draw.text((X, Y), tmpLine, font=font, fill=TEXTCOLOR) strLines.append(tmpLine) #print "100 %s, %s", X, Y #Y += 33 # intHeight * 1.1 #print "110" #print "120" strLine = word tmpLine = strLine else: tmpLine = strLine #print "Drawing Text" #print "tmpLine = " + tmpLine if not tmpLine == "": #draw.text((X, Y), tmpLine, font=font, fill=TEXTCOLOR) strLines.append(tmpLine) else: print "Nothing To Print" if True: #False: #Print On The Opacity Layer behind the text #print "making opacity background" #intLineEstimate = len(strLines) intRectWidth = intMaxDesiredLineWidth # intLineEstimate * 33 # 250 # calced by length of text intGradWidth = 40 intGradMaxOpacity = 210 sngGradVal = intGradMaxOpacity intX = 1920 intY = 1080 bgimg = PILImage.new('RGBA', (intX, intY), OPCOLOR) gradient = PILImage.new('L', (intX, 1)) #make veritical into horizontal for x in range(intX): if (x < (intRectWidth)): # + intGradWidth)): gradient.putpixel((x, 0), intGradMaxOpacity) #elif (x < (intRectWidth + intGradWidth)): # gradient.putpixel((x,0),int(sngGradVal)) # sngGradVal = sngGradVal - ((intGradMaxOpacity * 1.0) / intGradWidth) else: gradient.putpixel((x, 0), 0) # resize the gradient to the size of im... alpha = gradient.resize(bgimg.size) # put alpha in the alpha band of im... bgimg.putalpha(alpha) #draw bgimg onto im im.paste(bgimg, (0, 0), bgimg) #print on the text Y = max(10, ((imgHeight - 10) - (len(strLines) * 33)) / 2) if Y < 50: print "Y = " + str(Y) for strLine in strLines: if strLine <> "": bLines = True draw.text((X, Y), strLine, font=font, fill=TEXTCOLOR) Y += 33 #print strLine if bLines == True: print "Saving File " + strAPODPicsWithText + strAPODFileName im.save(strAPODPicsWithText + strAPODFileName) print "Done Building Cache Image With Text" except Exception as e: print str(e)
def base_image(width: int = IMAGE_SIZE, height: int = IMAGE_SIZE) -> Tuple[Image.Image, ImageDraw.ImageDraw]: image = Image.new('RGBA', (width, height)) draw = ImageDraw.Draw(image) return image, draw
def save_qtype(qtype_list, save_filename, mode): if mode == 'val': savepath = os.path.join('./eval', save_filename) # TODO img_pre = '/tempspace/zwang6/VQA/Images/mscoco/val2014' elif mode == 'test-dev': savepath = os.path.join('./test-dev', save_filename) # TODO img_pre = '/tempspace/zwang6/VQA/Images/mscoco/test2015' elif mode == 'test': savepath = os.path.join('./test', save_filename) # TODO img_pre = '/tempspace/zwang6/VQA/Images/mscoco/test2015' else: raise Exception('Unsupported mode') if os.path.exists(savepath): shutil.rmtree(savepath) if not os.path.exists(savepath): os.makedirs(savepath) for qt in qtype_list: count = 0 for t_question in stat_list: #print count, t_question if count < 40/len(qtype_list): t_question_list = t_question['q_list'] saveflag = False #print 'debug****************************' #print qt #print t_question_list #print t_question_list[0] == qt[0] #print t_question_list[1] == qt[1] if t_question_list[0] == qt[0] and t_question_list[1] == qt[1]: saveflag = True else: saveflag = False if saveflag == True: t_iid = t_question['iid'] if mode == 'val': t_img = Image.open(os.path.join(img_pre, \ 'COCO_val2014_' + str(t_iid).zfill(12) + '.jpg')) elif mode == 'test-dev' or 'test': t_img = Image.open(os.path.join(img_pre, \ 'COCO_test2015_' + str(t_iid).zfill(12) + '.jpg')) # for caption #print t_iid #annIds = caps.getAnnIds(t_iid) #anns = caps.loadAnns(annIds) #cap_list = [ann['caption'] for ann in anns] ans_list = t_question['ans_list'] draw = ImageDraw.Draw(t_img) for i in range(len(ans_list)): try: draw.text((10,10*i), str(ans_list[i])) except: pass ans = t_question['answer'] pred = t_question['pred'] if ans == -1: pre = '' elif ans == pred: pre = 'correct ' else: pre = 'failure ' #print ' aaa ', ans, pred ans = re.sub( '/', ' ', str(ans)) pred = re.sub( '/', ' ', str(pred)) img_title = pre + str(' '.join(t_question_list)) + '. a_' + \ str(ans) + ' p_' + str(pred) + '.png' count += 1 write_log(os.path.join(savepath,img_title), 'visualize_log.txt') t_img.save(os.path.join(savepath,img_title))
from PIL import Image, ImageDraw, ImageFont import matplotlib.font_manager image = Image.new('RGB', (640, 360), (255, 255, 255)) drawer = ImageDraw.Draw(image) font_list = matplotlib.font_manager.fontManager.ttflist def size_to_line_height(fontpath, size): font_sample = ImageFont.truetype(fontpath, size) sample_size = drawer.textsize("Hello python language", font=font_sample) offset = font_sample.getoffset("Hello python language") print(sample_size, offset) return sample_size[1] + offset[1] def drawText(text, x, y, font): size = drawer.textsize(text, font=font) offset = font.getoffset(text) print("size", size) print("offset", offset) print("size+offest", size[0] + offset[0], size[1] + offset[1]) drawer.text((x, y), text, fill='black', font=font) drawer.rectangle( (x, y, x + size[0] + offset[0], y + size[1] + offset[1]), outline='black') # drawing text font_size = size_to_line_height('/Library/Fonts/ヒラギノ角ゴ Pro W6.otf', 40)
def text_mode(cam): text = "" word = "" count_same_frame = 0 while True: img = cam.read()[1] img = cv2.resize(img, (640, 480)) img, contours, thresh = get_img_contour_thresh(img) old_text = text if len(contours) > 0: contour = max(contours, key = cv2.contourArea) if cv2.contourArea(contour) > 10000: text = get_pred_from_contour(contour, thresh) if old_text == text: count_same_frame += 1 else: count_same_frame = 0 if count_same_frame > 20: word = word + text count_same_frame = 0 elif cv2.contourArea(contour) < 1000: text = "" blackboard = np.zeros((480, 640, 3), dtype=np.uint8) b,g,r,a = 255,255,255,0 img_pil = Image.fromarray(blackboard) draw = ImageDraw.Draw(img_pil) draw.text((180,50), " ", font =ImageFont.truetype('malgun.ttf', 36), fill=(255, 0,0, 0)) draw.text((30, 100), "Predicted text-" + text, font = ImageFont.truetype('malgun.ttf', 36), fill = (255, 255, 0, 0)) line_break_idx = word.rfind("\n") #Line breaks on blackboard if line_break_idx==-1: if len(word) > 13: word += "\n" else: if len(word)-line_break_idx > 14: word += "\n" y0 = 150 dy = 50 for i, line in enumerate(word.split('\n')): y = y0 + i*dy line = join_jamos(line) draw.text((30, y), line, font=ImageFont.truetype('malgun.ttf', 36), fill=(255, 255, 255, 0)) blackboard = np.array(img_pil) cv2.putText(blackboard, " ", (450, 440), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 127, 0)) cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2) res = np.hstack((img, blackboard)) cv2.imshow("Recognizing gesture", res) cv2.imshow("thresh", thresh) keypress = cv2.waitKey(1) if keypress == ord('q') or keypress == ord('c'): break if keypress == 13: word = word + text count_same_frame = 0 if keypress == 8: word = word[:-1] if keypress == ord('c'): return 2 else: return 0
from PIL import Image, ImageDraw, ImageFont import math, os, sys, random from HelperFunctions import * # Parameters img_name = 'Armenian' font_size = (18, 24, 32) font_color = (0, 0, 0) font_path = os.path.join(os.getcwd(), 'DejaVuSans.ttf') folder_path = os.path.join(os.getcwd(), 'Unicode-Values', 'Armenian') # Create base image and draw object base_image = Image.new('RGB', (500, 500), (255, 255, 255)) base_draw = ImageDraw.Draw(base_image) # Load Font and get language data dejavu_font_s = ImageFont.truetype(font_path, font_size[0]) dejavu_font_m = ImageFont.truetype(font_path, font_size[1]) dejavu_font_l = ImageFont.truetype(font_path, font_size[2]) Armenian = readPath(folder_path) displayLangObject(Armenian) base_draw.text((250, 25), img_name, font=dejavu_font_l, fill=font_color, align='center', anchor='mm') x, y = 10, 30 for key in Armenian:
# to chromedriver in your computer driver = webdriver.Chrome('chromedriver',chrome_options=options) driver.get("https://web.whatsapp.com/") wait = WebDriverWait(driver, 100) print("Whatsapp connected") prev="1" while True: element1 = driver.find_elements_by_xpath('//*[@id="main"]/header/div[2]/div[1]') if(len(element1)>0): target=element1[0].text a=target.split(' ') reciever=a[0] image = Image.open('w.png') draw = ImageDraw.Draw(image) font = ImageFont.truetype('Charm-Regular', size=32) font2= ImageFont.truetype('Acme-Regular', size=26) (x, y) = (50, 50) message = "Wishing " + reciever.upper() + " and Family " color = 'rgb(255,58,249)' draw.text((x, y), message, fill=color, font=font) message="a very Happy New Year " (x, y) = (60, 87) draw.text((x, y), message, fill=color, font=font) (x,y) =(50,132) message="May Light always surround you" draw.text((x, y), message, fill=color, font=font) (x, y) = (500,300) name = ' - - - Tanay Mishra' color = 'rgb(18, 20, 234)'
def show_frame(self, set_number, seq_number, frame_number): self.load_annotations() # Will be needed # Check the frame was prepared if not self.is_frame_prepared(set_number, seq_number, frame_number): self.prepare_frame(set_number, seq_number, frame_number) if CaltechDataset.USE_CROPPING: image = Image.open(self.dataset_location + '/images-cropped/set{:02d}/V{:03d}.seq/{}.jpg'. format(set_number, seq_number, frame_number)) transform = np.load( self.dataset_location + '/images-cropped/set{:02d}/V{:03d}.seq/{}.transform.npy'. format(set_number, seq_number, frame_number)) else: image = Image.open(self.dataset_location + '/images/set{:02d}/V{:03d}.seq/{}.jpg'.format( set_number, seq_number, frame_number)) dr = ImageDraw.Draw(image) # Retrieve objects for that frame in annotations try: objects = self.annotations['set{:02d}'.format(set_number)][ 'V{:03d}'.format(seq_number)]['frames']['{}'.format( frame_number)] except KeyError as e: objects = None # Simply no objects for that frame if objects: for o in objects: pos = (o['pos'][1], o['pos'][0], o['pos'][3], o['pos'][2] ) # Convert to (y, x, h, w) if CaltechDataset.USE_CROPPING: pos = transform_cropped_pos(pos, transform) if o['lbl'] in ['person']: good = True # Remove objects with very small width (are they errors in labeling?!) if pos[3] < CaltechDataset.MINIMUM_WIDTH: good = False if o['occl'] == 1: if type(o['posv']) == int: good = False else: visible_pos = (o['posv'][1], o['posv'][0], o['posv'][3], o['posv'][2] ) # Convert to (y, x, h, w) if CaltechDataset.USE_CROPPING: visible_pos = transform_cropped_pos( visible_pos, transform) if visible_pos[2] * visible_pos[ 3] < CaltechDataset.MINIMUM_VISIBLE_RATIO * pos[ 2] * pos[3]: good = False pos = visible_pos if good: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='blue') else: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='pink') else: dr.rectangle( (pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='black') clas_negative = np.load( self.dataset_location + '/prepared/set{:02d}/V{:03d}.seq/{}.negative.npy'.format( set_number, seq_number, frame_number)) for i in range(clas_negative.shape[1]): y, x, anchor_id = clas_negative[:, i] dr.rectangle( (CaltechDataset.OUTPUT_CELL_SIZE * x, CaltechDataset.OUTPUT_CELL_SIZE * y, CaltechDataset.OUTPUT_CELL_SIZE * (x + 1) - 1, CaltechDataset.OUTPUT_CELL_SIZE * (y + 1) - 1), outline='red') clas_positive = np.load( self.dataset_location + '/prepared/set{:02d}/V{:03d}.seq/{}.positive.npy'.format( set_number, seq_number, frame_number)) for i in range(clas_positive.shape[1]): y, x, anchor_id = clas_positive[:, i] pos = self.get_anchor_at(anchor_id, y, x) dr.rectangle( (CaltechDataset.OUTPUT_CELL_SIZE * x, CaltechDataset.OUTPUT_CELL_SIZE * y, CaltechDataset.OUTPUT_CELL_SIZE * (x + 1) - 1, CaltechDataset.OUTPUT_CELL_SIZE * (y + 1) - 1), outline='green') dr.rectangle((pos[1], pos[0], pos[1] + pos[3], pos[0] + pos[2]), outline='green') image.show()