def full_image_to_slice(path, slice): ''' From a 3D image, save a slice corresponding to the index. Normalize the pixel image. Return the minimum size of the image. :param path: :param slice: :return: ''' items = [f for f in listdir(path) if isfile(join(path, f))] min_size_x, min_size_y = [], [] for name in items: new_name = name[:-7] + '.png' image = sitk.ReadImage(path + "/" + name) image_np = sitk.GetArrayFromImage(image) if (path == 'T1'): if image_np.shape[1] < slice: continue image_np = image_np[:, slice, :].astype(np.int16) else: if image_np.shape[0] < slice: continue image_float_and_flip = np.flip(image_np[slice, :, :].astype( np.float).T).copy() # rescale image to 0-255 range image_np = (image_float_and_flip / image_float_and_flip.max() * 255).astype(np.uint8) min_size_x.append(image_np.shape[0]) min_size_y.append(image_np.shape[1]) png.from_array(image_np, 'L').save(path + "_slices/" + new_name) return min_size_x, min_size_y
def convert_image(i, scene, img_depth, image, label): idx = int(i) + 1 if idx in train_images: train_test = "training" else: #assert idx in test_images, "index %d neither found in training set nor in test set" % idx if idx not in test_images: print("leaving convert image early. index {} is processed".format( idx)) return train_test = "testing" folder = "%s/%s/%s" % (out_folder, train_test, scene) if not os.path.exists(folder): os.makedirs(folder) img_depth = img_depth * 1000.0 png.from_array(img_depth, 'L;16').save("%s/%05d_depth.png" % (folder, i)) depth_visualization = visualize_depth_image(img_depth) # workaround for a bug in the png module depth_visualization = depth_visualization.copy() # makes in contiguous shape = depth_visualization.shape depth_visualization.shape = (shape[0], np.prod(shape[1:])) depth_image = png.from_array(depth_visualization, "RGBA;8") depth_image.save("%s/%05d_depth_visualization.png" % (folder, i)) imsave("%s/%05d_colors.png" % (folder, i), image) ground_truth = process_ground_truth(label) imsave("%s/%05d_ground_truth.png" % (folder, i), ground_truth)
def field_profile_and_save(x2_position, filename): Bx = np.ndarray( (xsize,ysize) , dtype=float) By = np.ndarray( (xsize,ysize) , dtype=float) # initialize for i in range(xsize): for j in range(ysize): Bx[i,j] = 0.0 By[i,j] = 0.0 points = points_in_sphere(3.5) for p in points: add_current(Bx,By,25+p[0],25+p[1],1.0/len(points)) points = points_in_sphere(3.5) for p in points: add_current(Bx,By,x2_position+p[0],x2_position+p[1],-1.0/len(points)) # color and write file a = np.ndarray((xsize,ysize,3), dtype=np.uint8) for i in range(xsize): for j in range(ysize): a[i,j] = field_to_log_color(1.0, -80, 255, math.sqrt(Bx[i,j]**2 + By[i,j]**2)) f= open(filename, 'w+') png.from_array(a, mode='RGB').save(f) return f
def dump_region_to_png(pts, fname): ps = map(lambda p: p.to_pair(), pts) scale = 255 / float(len(ps) - 1) scales = 10 maximalx = reduce(lambda o, p: max(o, p[0]), ps, 0) * scales maximaly = reduce(lambda o, p: max(o, p[1]), ps, 0) * scales minimalx = reduce(lambda o, p: min(o, p[0]), ps, maximalx) * scales minimaly = reduce(lambda o, p: min(o, p[1]), ps, maximaly) * scales img = [[(0, 0, 0) for x in range(int(maximalx + minimalx + 2))] for y in range(int(maximaly + minimaly + 2))] for i, (x, y) in enumerate(ps): # print>>sys.stderr, i, x, y, len(img), int(y*scales+1) #print>>sys.stderr, 255-int(i*scale) img[int(y * scales)][int(x * scales)] = (max(0, 255 - int(i * scale)), min(255, int(i * scale)), 0) img[int(y * scales + 1)][int(x * scales)] = (max(0, 255 - int(i * scale)), min(255, int(i * scale)), 0) img[int(y * scales - 1)][int(x * scales)] = (max(0, 255 - int(i * scale)), min(255, int(i * scale)), 0) img[int(y * scales)][int(x * scales + 1)] = (max(0, 255 - int(i * scale)), min(255, int(i * scale)), 0) img[int(y * scales)][int(x * scales - 1)] = (max(0, 255 - int(i * scale)), min(255, int(i * scale)), 0) ln = len(img) for y in range(len(img)): print>>sys.stderr, fname, y, 'of', ln, ' \r', sys.stdout.flush() img[y] = reduce(lambda o, p: o + list(p), img[y], []) # print png.from_array(img, 'RGB').save(fname)
def displaypgm(data, width): a = [] w = int(width) for i in range(len(data)/w): row = [data[x + (i * w)] for x in range(w)] a.append(row) png.from_array(a, "L").save("out.png")
def convert_image(iffImageFile,outName): print iffImageFile img=MayaImage(iffImageFile) oGTruth, oDepth, oDepthVisualization = get_output_names(outName) dImage, dvImage = img.getDepthImages() rgbImage = img.getRGBImage() x1,x2,y1,y2 = autocrop(convert_to_PIL(rgbImage)) oRgb = rgbImage oRgb = oRgb[x2:y2,:] oRgb = oRgb[:,x1:y1] oRgb = np.reshape(oRgb,(y2-x2,(y1-x1)*3)) png.from_array(oRgb, 'RGB;8').save(oGTruth) oDvImage = dvImage oDvImage = np.reshape(oDvImage,(img.height(),img.width(),4)) oDvImage = oDvImage[x2:y2,:] oDvImage = oDvImage[:,x1:y1] oDvImage = np.reshape(oDvImage,(y2-x2,(y1-x1)*4)) #png.from_array(oDvImage, 'RGBA;8').save(oDepthVisualization) oDImage = np.reshape(dImage,(img.height(),img.width(),1)) oDImage = oDImage[x2:y2,:] oDImage = oDImage[:,x1:y1] oDvImage = np.reshape(oDImage,(y2-x2,(y1-x1))) png.from_array(oDvImage, 'L;16').save(oDepth) #shutil.copy(oGTruth, oGTruth.replace("ground_truth","colors")) return iffImageFile
def to_png(self, filename='qr-code.png', size=10, border=4): qr_code = np.pad(self.matrix, 4, mode='constant', constant_values=0) qr_code = np.repeat(np.repeat(qr_code, size, axis=0), size, axis=1) replace = {-1: 200, 1: 0, 0: 255} qr_code_list = [[replace[j] for j in i] for i in np.swapaxes(qr_code, 0, 1)] png.from_array(qr_code_list, 'L').save(filename)
def draw_solution(solution: List[int], path: str) -> None: """ Converts solution to eight queen problem into its png representation. Args: solution: List of integers. Each integer represents row in which queen is placed, and numbers position on a list represents column of a chessboard. path: place where png file will be saved. Returns: None """ board = _create_board( field_px_size=FIELD_PX_SIZE, n_fields=SIZE, dark_color=GREY_COLOR, light_color=WHITE_COLOR, ) queen = _read_queen_array() for row, col in enumerate(solution): board = _place_queen_on_board(row, col, board, queen, SIZE) # this will give image nice black border around it board = np.pad(board, pad_width=3, mode="constant", constant_values=BLACK_COLOR) png.from_array(board, mode="L").save(path)
def update(): global drawmod, cmlInit, last_render_time, frame # diffusion cml.iterate() # calculate various statistics used for control and influencing musical parameters stats.update(cml.matrix, cml.iter) # try some spin control # print 'spinTrans %d spinTrend %d lastSpinTrend %d alpha %.4f' % (stats.spinTrans, stats.spinTrend, lastSpinTrend, cml.a) # experiment with spin control - number of spin transitions > threshold, or else decrease alpha # if a is chaotic, it will search and find a more stable (but probably still chaotic) value reducing spin transitions print (cml.iter), if stats.spinTrend > 500: print "reducing alpha" cml.a = cml.a - 0.001 if cml.iter > 1 and cml.iter % drawmod == 0: # calculating fps with goal of 30fps current_time = time.time() render_time = current_time - last_render_time last_render_time = current_time fps = round(1 / render_time) # try to get fps up to 30. drawmod = 1 scaled = (cml.matrix + 1) * 64 done = np.array(scaled).astype(short).tolist() # print(done) ## Display the data filename = "frame" + str(frame) + ".png" png.from_array(done, "L").save(filename) frame += 1
def png(self): path = config.renders_directory + self.id + ".png" if os.path.isfile(path): return path os.makedirs(config.renders_directory) array = list() for i in range(0, self.width): array.append(list()) for assignment in Assignment.objects(rendering=self): for y in range(assignment.y, assignment.y + assignment.height): for x in range(assignment.x, assignment.x + assignment.width): for s in range(0, len(assignment.pixels)): array[x][y] = [ assignment.pixels[4 * s + 0], assignment.pixels[4 * s + 1], assignment.pixels[4 * s + 2], assignment.pixels[4 * s + 3] ] png.from_array(array, 'RGBA').save(path) return path
def encode_to_image(filename): filesize = os.path.getsize(filename) print "filename",filename,"filesize",filesize width = int(math.sqrt(filesize)) # try to keep the image almost square f = open(filename,"rb") byte = f.read(1) pixelarray = [] rowarray = [] row,col = 0,0 while byte != "": byte = int(binascii.hexlify(byte), 16) # convert each byte to pixels, using 3 bits for B and G, and 2 bits for R pixel = [(byte & 0b11000000) >> 6,(byte & 0b00111000) >> 3,(byte & 0b00000111)] rowarray.extend(pixel) col += 1 if (col == width): col = 0 pixelarray.append(rowarray) rowarray=[] byte = f.read(1) while (col < width): # pad the rest of the last row with black rowarray.extend([0,0,0]) col +=1 pixelarray.append(rowarray) png.from_array(pixelarray,'RGB').save(filename[:-4]+".png") f.close()
def writePngImages(self): #Loop through each texture for tex in self.texList: self.bs.seek_set(0) offset = self.bs.tell() % 4 self.bs.seek_cur(offset) #Look for PVRT file header if not self.bs.find(PvmArchive.PVRT): #If not found, raise an error print("PVRT not found: 0x%x" % self.bs.tell()) return 0 #Length of pvr texture pvrLen = self.bs.readUInt() self.bs.setOffset() #Create PvrImage to convert bitmap print("Name: %s, Pos: 0x%x" % (tex['name'], self.bs.tell())) pvr = PvrTexture(self.bs, False, True) bitmap = pvr.getBitmap() imgName = "output/" + tex['name'] + '.png' png.from_array(bitmap, 'RGBA').save(imgName) #img = Image.open(imgName) #img = img.rotate(180) #img.save(imgName) print("") return 1
def save_output(self, imgpath): '''Save label in segmented folder. ''' label = np.uint16(self.label) directory = join(self.argdict['outputdir'], 'segmented') filename = basename(imgpath).split('.')[0] + '_{0}.png'.format(self.obj) png.from_array(label, 'L').save(join(directory, filename))
def StoreNoiseTextureLDR(Texture,OutputPNGFilePath,nRank=-1): """This function stores the given texture to a standard low-dynamic range png file with four channels and 8 bits per channel. \param Texture An array of shape (Height,Width) or (Height,Width,nChannel). The former is handled like (Height,Width,1). If nChannel>4 the superfluous channels are ignored. If nChannel<4 the data is expanded. The alpha channel is set to 255, green and blue are filled with black or with duplicates of red if nChannel==1. It is assumed that each channel contains every integer value from 0 to nRank-1 exactly once. The range of values is remapped linearly to span the range from 0 to 255. \param OutputPNGFilePath The path to the output png file including the file format extension. \param nRank Defaults to Width*Height if you pass a non-positive value.""" # Scale the array to an LDR version if(nRank<=0): nRank=Texture.shape[0]*Texture.shape[1]; Texture=np.asarray((Texture*256)//nRank,dtype=np.uint8); # Get a three-dimensional array if(len(Texture.shape)<3): Texture=Texture[:,:,np.newaxis]; # Generate channels as needed if(Texture.shape[2]==1): Texture=np.dstack([Texture]*3+[255*np.ones_like(Texture[:,:,0])]); elif(Texture.shape[2]==2): Texture=np.dstack([Texture[:,:,0],Texture[:,:,1]]+[np.zeros_like(Texture[:,:,0])]+[255*np.ones_like(Texture[:,:,0])]); elif(Texture.shape[2]==3): Texture=np.dstack([Texture[:,:,0],Texture[:,:,1],Texture[:,:,2]]+[255*np.ones_like(Texture[:,:,0])]); elif(Texture.shape[2]>4): Texture=Texture[:,:,:4]; # Save the image png.from_array(Texture,"RGBA;8").save(OutputPNGFilePath);
def generate_dhm_splat_tile(x: int, y: int, zoom: int): # load associated tile entry from db tile = get_or_initialize_tile(x, y, zoom) # load or generate dhm information np_dhm = tile.heightmap if not np_dhm: # generate tile in db np_dhm = generate_dhm_db(x, y, zoom) # create empty image np_image = np.zeros((TILE_SIZE_PIXEL, TILE_SIZE_PIXEL, 4), dtype=np.uint16) # add heightmap to the image # we expect values in centimeters as unsigned integer with values from 0-8500000 # which requires 20bit to store. In the 16-bit per channel image this requires # 1,5 channels so we store it in RRGgbbaa pass # FIXME: maybe it is currently sufficiant to use two complete channels (RRGG) # Heightmap: RRGgbbaa # Vegetation Splatmap: rrgGBbaa # write the file including the alpha mask output_file = DHM_SPLAT_FILE.format(DHM_SPLAT_IDENTIFIER, zoom, y, x) png.from_array(np_image, 'RGBA').save(output_file)
def convert_image(i, scene, img_depth, image, label): idx = int(i) + 1 if idx in train_images: train_test = "training" else: assert idx in test_images, "index %d neither found in training set nor in test set" % idx train_test = "testing" folder = "%s/%s/%s" % (out_folder, train_test, scene) if not os.path.exists(folder): os.makedirs(folder) img_depth *= 1000.0 png.from_array(img_depth, 'L;16').save("%s/%05d_depth.png" % (folder, i)) depth_visualization = visualize_depth_image(img_depth) # workaround for a bug in the png module depth_visualization = depth_visualization.copy() # makes in contiguous shape = depth_visualization.shape depth_visualization.shape = (shape[0], np.prod(shape[1:])) depth_image = png.from_array(depth_visualization, "RGBA;8") depth_image.save("%s/%05d_depth_visualization.png" % (folder, i)) imsave("%s/%05d_colors.png" % (folder, i), image) ground_truth = process_ground_truth(label) imsave("%s/%05d_ground_truth.png" % (folder, i), ground_truth)
def testfromarrayWrong(self): """Test incorrect mode handling""" try: png.from_array([[1]], 'gray') except png.Error: return assert 0, "Expected from_array() to raise png.Error exception"
def main(): if len(sys.argv) < 3: print("Usage: python visualize.py [in_file] [out_file]") sys.exit(-1) inFile = sys.argv[1] outFile = sys.argv[2] with open(inFile, mode='rb') as file: # import file to read as a binary byte_file = file.read() pixel_values = make_pixel_array(byte_file) image_size = int(len(pixel_values) ** 0.5) # splits values into arrays of equal size to make the rows/columns of the image pixel_array=[pixel_values[x:x+image_size] for x in range(0, len(pixel_values), image_size)] # truncates pixel info to ensure a square image if len(pixel_array[-1]) != image_size: pixel_array = pixel_array[:-1] if (outFile[-4:]) != ".png": outFile += ".png" #print(pixel_array) #if you want to see individual pixel values, uncomment # creating the pixel array makes saving the image easy, PIL-like png.from_array(pixel_array, 'RGB').save(str(outFile))
def parabolaGen(h, l, open_paint=False, file_name="parabola_fine_vertical", ceil=math.ceil): if _inputParser_(h, l): t = time() h = abs(int(h)) l = abs(int(l)) a = -4 * h / (l * l) #Records the heights of the parabola at a certain position on the x-axis y = [a * (i + 0.5) * (i + 0.5 - l) for i in range(l)] p = [[] for i in range(h)] for row in range(h): dThreshold = h - 1 - row for pix in range(ceil(l / 2)): pixVal = 0 if y[pix] > dThreshold: pixVal = y[pix] - dThreshold if pixVal > 1: pixVal = 1 p[row].append(ceil(pixVal * 255)) for row in range(h): for pix in range(int(l / 2) - 1, -1, -1): p[row].append(p[row][pix]) png.from_array(p, 'L').save(file_name + ".png") print("Parabola generation took ", time() - t, " seconds.") if open_paint: call(["mspaint", file_name + ".png"], shell=True)
def preprocess_gq(color_im,depth_im,depth_im_mask = None): if depth_im_mask is not None: # to mask the relevant parts of the image, if a mask is available depth_im = depth_im_dif #convert to pypng format color_im = (65535*((color_im*color_im.min()/color_im.ptp())).astype(np.uint16)) color_im = np.reshape(color_im, (-1, color_im.shape[1]*3)) # import matplotlib.pyplot as plt # plt.imshow(color_im) # plt.show() #convert depth scale inputresolution = 0.0001 #(meter/unit) outputresolution = 1 #(meter/unit) mind = .2 maxd = 15 array = depth_im[:] array_in_meters = array*inputresolution array_in_meters[array_in_meters < mind] = mind array_in_meters[array_in_meters > maxd] = maxd array_in_meters += 0.2 #arbitrary altering the distances to compare better to the dex net trainingset, needs be undone after evaluating the quality array = array_in_meters/outputresolution depth_im = array[:] #save in dexnetfolder dexnet_filename_color = 'color_0.png' dexnet_filename_depth = 'depth_0.npy' png.from_array(color_im,'RGB').save(dexnet_loadpath+"/data/own/"+dexnet_filename_color) np.save(dexnet_loadpath+"/data/own/"+dexnet_filename_depth,np.array(depth_im,dtype = 'float'))
def parabolaGen(h, l, open_paint=False, file_name="parabola_fine_horizontal", sqrt=math.sqrt, ceil=math.ceil): if _inputParser_(h, l): t = time() h = abs(int(h)) l = abs(int(l)) a = -4 * h / (l*l) #Records the heights of the parabola at a certain position on the x-axis x = [(sqrt(a*(a*l**2+4*i+2))+a*l) / (2*a) for i in range(h-1, -1, -1)] p = [[] for i in range(h)] for dThreshold in range(1, ceil(l/2)+1): for pix in range(h): pixVal = 0 if dThreshold > x[pix]: pixVal = dThreshold - x[pix] if pixVal > 1: pixVal = 1 p[pix].append(ceil(pixVal * 255)) for row in range(h): for pix in range(int(l/2)-1, -1, -1): p[row].append(p[row][pix]) png.from_array(p, 'L').save(file_name+".png") print("Parabola generation took ", time() - t, " seconds.") if open_paint: call(["mspaint", file_name+".png"], shell=True)
def createHeatMap(): global mat maxVal = 0 newMat = [[0 for x in range(windowWidth * 2)] for y in range(windowHeight)] # copy value in matrix (which is bigger than 0) to 3x3 neighborhood (for better visibility in final image) for x in range(1, windowHeight - 1): for y in range(2, windowWidth * 2, 2): val = mat[x][y] if (val > 0): for k in range(-1, 2): for j in range(-2, 3, 2): if (mat[x + k][y + j] <= val): newMat[x + k][y + j] = val # get max click count for x in range(windowHeight): for y in range(0, windowWidth * 2, 2): if (newMat[x][y] > maxVal): maxVal = newMat[x][y] # convert click counts to intensity value if (maxVal != 0): for x in range(windowHeight): for y in range(0, windowWidth * 2, 2): newMat[x][y] *= int(255 / maxVal) if (newMat[x][y] > 0): newMat[x][y + 1] = 255 # save image png.from_array(newMat, 'LA').save("heat_map.png")
def displaypgm(bytes, width, name): a = [] w = int(width) for i in range(len(bytes) / w): row = [bytes[x + (i * w)] for x in range(w)] a.append(row) png.from_array(a, "L").save(name)
def parabolaGen(h, l, open_paint=False, file_name="parabola"): if _inputParser_(h, l) is not None: t = time.time() h = abs(int(h)) l = abs(int(l)) a = -4 * h / (l * l) y = [_mround_(a * (i + 0.5) * (i + 0.5 - l)) for i in range(l)] p = [] for i in range(h): p.append([]) drawThreshold = h - 1 - i for j in range(math.ceil(l / 2)): pixVal = 0 if y[j] > (drawThreshold): pixVal = y[j] - drawThreshold if pixVal > 1: pixVal = 1 p[i].append(math.ceil(pixVal * 255)) for row in range(h): for pix in range(int(l / 2) - 1, -1, -1): p[row].append(p[row][pix]) png.from_array(p, 'L').save(file_name + ".png") print("Parabola generation took ", time.time() - t, " seconds.") if open_paint: call(["mspaint", file_name + ".png"], shell=True)
def write_heatmap_to_png(a, filename, scale=1): a_shape = np.shape(a) colored = np.ndarray([a_shape[1] * scale, a_shape[2] * scale, 3], np.uint8) a_max = np.max(a) a_min = np.min(a) abs_max = max(abs(a_max), abs(a_min)) for i in range(a_shape[1]): for j in range(a_shape[2]): val = a[0, i, j, 0] for n in range(scale): for m in range(scale): ind_i = i * scale + n ind_j = j * scale + m colored[ind_i, ind_j, 0] = 0 colored[ind_i, ind_j, 1] = 0 colored[ind_i, ind_j, 2] = 0 if val > 0: colored[ind_i, ind_j, 0] = abs(val * (255 / (abs_max + 0.001))) else: colored[ind_i, ind_j, 2] = abs(val * (255 / (abs_max + 0.001))) png.from_array(colored, 'RGB').save(filename)
def draw_table(results, size, out_name="/tmp/table.png"): #7C2529 sat_color = (0xF1, 0xBE, 0x48) unsat_color = (0x7C, 0x25, 0x29) error_color = (0xFF, 0x00, 0x00) background_color = (0xFF, 0xFF, 0xFF) box_width = 8 box_height = 8 width = box_width * size height = box_height * size arr = [] for i in range(0, height): na = [] for j in range(0, width): na.append(background_color) arr.append(na) for i in range(0, size): for j in range(0, size): if results[i][j] == 0: continue color = error_color if results[i][j] == 10: color = sat_color elif results[i][j] == 20: color = unsat_color for x in range(box_width * i, box_width * i + box_width): for y in range(box_height * j, box_height * j + box_height): arr[y][x] = color png.from_array(arr, 'RGB').save(out_name)
def save_output(self, imgpath): '''Save img as output. ''' label = np.uint16(self.img) directory = join(self.argdict['outputdir'], 'processed') filename = basename(imgpath).split('.')[0] + '.png' png.from_array(label, 'L').save(join(directory, filename))
def writePngImages(self): #Seek to texture offset self.bs.seek_set(self.texOfs) #Check offset for texture definition iff = self.bs.readUInt() if iff != ShenmueModel.TEXD: return 0 iffLen = self.bs.readUInt() #Read number of textures nbTex = self.bs.readUInt() texBase = os.path.splitext(self.fp)[0] #Loop through each texture for i in range(nbTex): #Look for pvr file header if not self.bs.find(ShenmueModel.PVRT): return 0 #Length of pvrFile pvrLen = self.bs.readUInt() pvr = PvrTexture(self.bs, False, True) bitmap = pvr.getBitmap() if len(bitmap) == 0: continue texName = "output/%s_%02d.png" % (texBase, i) print(texName) png.from_array(bitmap, 'RGBA').save(texName) return 1
def __call__(self, args): super(ScreenshotCommand, self).__call__(args) screenshot = Screenshot(self.pebble) screenshot.register_handler("progress", self._handle_progress) self.progress_bar.start() try: image = screenshot.grab_image() except ScreenshotError as e: if self.pebble.firmware_version.major == 3 and self.pebble.firmware_version.minor == 2: # PBL-21154: Screenshots failing with error code 2 (out of memory) raise ToolError( str(e) + " (screenshots are known to be broken using firmware 3.2; try the emulator.)" ) else: raise ToolError(str(e) + " (try rebooting the watch)") if not args.no_correction: image = self._correct_colours(image) image = self._roundify(image) self.progress_bar.finish() filename = self._generate_filename( ) if args.filename is None else args.filename png.from_array(image, mode='RGBA;8').save(filename) print("Saved screenshot to {}".format(filename)) if not args.no_open: self._open(os.path.abspath(filename))
def generate(self, output_path, n): if self.generate_function: img = self.generate_function(n) img = np.reshape(img, (n, 28, 28)) img = np.reshape(img, (n * 28, 28)) img = (img * 255.0).astype(np.uint8) png.from_array(img, mode='L').save(output_path)
def cifar10_pickle_to_png(cifar10_path): label_path = os.path.join(cifar10_path, 'batches.meta') meta_file = open(label_path, 'rb') labels = pickle.load(meta_file, encoding="ASCII") for fpath in os.scandir(cifar10_path): if 'data' not in fpath.name and 'test' not in fpath.name: continue f = open(fpath, 'rb') d = pickle.load(f, encoding='bytes') # decode utf8 d_decoded = {} for k, v in d.items(): d_decoded[k.decode('utf8')] = v d = d_decoded f.close() for i, filename in enumerate(d['filenames']): folder = os.path.join( cifar10_path, 'cifar10', fpath.name, labels['label_names'][d['labels'][i]], ) os.makedirs(folder, exist_ok=True) q = d['data'][i] print(filename) with open(os.path.join(folder, filename.decode()), 'wb') as outfile: png.from_array(q.reshape((32, 32, 3), order='F').swapaxes(0, 1), mode='RGB').save(outfile)
def main(parentWidget=None, isQt=True): """ Convenience function for basic use case. Get screenshot with ScreenshotOverlay, pass image to AnnotationWindow, and get the final edited image back. :parentWidget: optional QObject to use as parent for the windows :isQt: bool for whether there is an existing QApp running. Assumed True. :return: byte buffer object of image in PNG format """ if not isQt: app = QApplication(sys.argv) try: snap = ScreenshotOverlay(parentWidget) with ScreenshotContext(snap): res = snap.exec_() if res: draw = AnnotationWindow(snap.img, parentWidget) draw.exec_() buf = BytesIO() s = draw.final_img.shape # png needs it converted into 2D array f = numpy.reshape(draw.final_img, (-1, s[1] * s[-1])) png.from_array(f, "RGBA;8").save(buf) return buf except: raise finally: if not isQt: app.quit()
def make_svg_file(pixels, fname, grayscale=False): if grayscale: pngimg = png.from_array(pixels, 'L') else: pngimg = png.from_array(pixels, 'RGB') pngfile = io.BytesIO() pngimg.save(pngfile) image = Image.open(pngfile).convert('RGB') imagedata = image.load() svgdata = '' svgdata += ('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n') svgdata += ( '<svg id="svg2" xmlns="http://www.w3.org/2000/svg" version="1.1" width="%(x)i" height="%(y)i" viewBox="0 0 %(x)i %(y)i">\n' % { 'x': image.size[0], 'y': image.size[1] }) for y in range(image.size[1]): for x in range(image.size[0]): rgb = imagedata[x, y] rgb = '#%02x%02x%02x' % rgb svgdata += ( '<rect width="1" height="1" x="%i" y="%i" fill="%s" />\n' % (x, y, rgb)) svgdata += ('</svg>\n') with open(fname, 'w') as f: f.write(svgdata)
def test_calculate_gradient_equals_zero_rectangle_area(self): pixels = (np.random.rand(150 * 150) < 0.5).astype(np.int16) pixels = pixels.reshape(150, 150) for x in range(0, 150): for y in range(0, 150): pixels[x][y] = 0 pixels[0][0] = 0 pixels[0][1] = 0 pixels[0][2] = 0 pixels[1][0] = 0 pixels[1][1] = 0 pixels[1][2] = 0 pixels[2][0] = 0 pixels[2][1] = 0 pixels[2][2] = 0 png.from_array(pixels, 'L').save("../Dane/rectangle__foo.png") myImage = Image("../Dane/rectangle__foo.png", 0) position = Position(1, 1) size = Size(10, 10) rArea = RectangleArea(myImage, position.x, position.y, size.height, size.width) histogram = rArea.create_histogram() self.assertAlmostEqual(histogram.get(0), 0.0, delta=0.01) self.assertAlmostEqual(histogram.get(1), 0.0, delta=0.01) os.remove("../Dane/rectangle__foo.png")
def encode(message): """Encode the message string into images based on PNGs in pool/, and store the resulting images in encoded/. """ if len(message) == 0: return pool_list = ["pool/" + f for f in os.listdir("pool/") if '.png' in f] assert len(message) <= max_length() int_list = [ord(c) for c in message] + [0] for i in range(len(pool_list)): pool_im = mpng.read_png_int(pool_list[i]) assert pool_im.shape[2] == 3 #check if RGB image # print(len(tiles(pool_im.shape[0], pool_im.shape[1])), (pool_im.shape[0]//2) * (pool_im.shape[1]//8)) for tile in tiles(pool_im.shape[0], pool_im.shape[1]): encode_int(pool_im, tile, int_list.pop(0)) if len(int_list) == 0: break png.from_array(pool_im, mode='RGB').save("encoded/image_{0}.png".format(i)) if len(int_list) <= 1: break return
def test_calculate_gradient_with_same_difference_circle_area(self): pixels = (np.random.rand(150 * 150) < 0.5).astype(np.int16) pixels = pixels.reshape(150, 150) for x in range(0, 150): for y in range(0, 150): pixels[x][y] = 0 pixels[0][0] = 0 pixels[0][1] = 100 pixels[0][2] = 0 pixels[1][0] = 150 pixels[1][1] = 0 pixels[1][2] = 250 pixels[2][0] = 0 pixels[2][1] = 200 pixels[2][2] = 0 png.from_array(pixels, 'L').save("../Dane/circle__foo.png") myImage = Image("../Dane/circle__foo.png", 0) position = Position(50, 50) radius = 50 cArea = CircleArea(myImage, position.x, position.y, radius) histogram = cArea.create_histogram() for x in range(0, 8): if histogram.get(x) != 0: print(str(x) + ": " + str(histogram.get(x))) self.assertAlmostEqual(histogram.get(5), 0.0, delta=0.05) self.assertAlmostEqual(histogram.get(6), 0.0, delta=0.05) os.remove("../Dane/circle__foo.png")
def write_tuple(rounds, places, run_return): out_name = "images/" + run_return + "-r" + str(rounds) + "-p" + '-'.join(map(str, places)) + ".png" #7C2529 difference = (0xFF, 0x00, 0x00) no_difference = (0x00, 0x00, 0xFF) background_color = (0xFF, 0xFF, 0xFF) box_width = 1 box_height = 1 image_width = 16 image_height = 3 width = box_width*image_width height = box_height*image_height arr = [] for i in range(0, height): na = [] for j in range(0, width): na.append(background_color) arr.append(na) for i in range(0, rounds): bx = i % image_width by = i // image_width for x in range(box_width*bx, box_width*bx + box_width): for y in range(box_height*by, box_height*by + box_height): arr[y][x] = no_difference for i in places: bx = i % image_width by = i // image_width for x in range(box_width*bx, box_width*bx + box_width): for y in range(box_height*by, box_height*by + box_height): arr[y][x] = no_difference png.from_array(arr, 'RGB').save(out_name)
def parabolaGen(h, l, open_paint=False, file_name="parabola_antialiased"): """parabolaGen help: parabolaGen(h, l) Let h be the height of the parabola. It must be a number greater than 0. Let l be the length of the parabola. It must also be a greater than 0. You can also use pGen(h, l) as a shortcut. """ if _inputParser_(h, l): t = time() h = abs(ceil(h)) l = abs(ceil(l)) a = -4 * h / (l * l) sff = round(h + (l**2 - 16 * h**2) / (16 * h)) #Records the heights of the parabola at a certain position on the x-axis if sff <= h: p = parabola_vBiased(h, sff, l, a) + parabola_hBiased(h, sff, l, a) else: p = parabola_vBiased(h, h, l, a) for row in range(h): p[row] += [p[row][pix] for pix in range(int(l / 2) - 1, -1, -1)] from_array(p, 'L').save(file_name + ".png") print("Parabola generation took", time() - t, "seconds.") if open_paint: call(["mspaint", file_name + ".png"], shell=True) return
def _work(self, f): consider = True if self.re is None else f.find(self.re) > -1 if consider: print(f"Processing {f}") fp = pathlib.Path(self.source_path, f).absolute() #tarpath= f.replace(".tar.gz" , ".log") year = re.findall("F\d{2}(\d{4}).v", f)[0] image = self.helper.read_img_path(fp) print(f"-- Extraction Started") for country in self.countries: op = pathlib.Path(self.dest_path, f"{country}_{year}.png").absolute() if not os.path.exists(op): print(f"--- Country - {country}") try: subimg = self.helper.subset_country(image, country) print(subimg.shape) png.from_array(subimg[0, :, :], 'L').save(op) except Exception as e: print(e) print(f"Failed - {op}") #shutil.copyfile(pathlib.Path(expath , f).absolute() , pathlib.Path(expath , f).absolute()) print(f"-- Extraction done")
def request_overlay(self, request): pixels = np.zeros((256, 256, 4), np.uint8) pixels[:] = (255, 0, 0, 100) pixels[::16, :, :] = (255, 0, 0, 255) pixels[:, ::32, :] = (255, 0, 0, 255) buf = io.BytesIO() png.from_array(pixels, mode="RGBA").save(buf) return web.Response(body=buf.getvalue())
def mk_png(self, png_name): if self.count: png.from_array([row[: self.count] for row in self.grid], "L").save(png_name) else: # no audio data, make a 1x1 png png.from_array([(0, 0)], "L").save(png_name) return True
def test_render_image(self, f): pix2d = [[0]*(self.width*4) for i in range(self.height)] for cube in self.cubes: if (cube.position.x, cube.position.y) in self.positions2d: pix2d[cube.position.y][((cube.position.x+1) * 4)-4] = cube.colour.r pix2d[cube.position.y][((cube.position.x+1) * 4)-3] = cube.colour.g pix2d[cube.position.y][((cube.position.x+1) * 4)-2] = cube.colour.b pix2d[cube.position.y][((cube.position.x+1) * 4)-1] = cube.colour.a png.from_array(pix2d, 'RGBA').save(f)
def exportComparison(data, reconstruction, filename): img = np.empty([data.shape[3] * 2, data.shape[2] * data.shape[0]], dtype = np.uint8); for imageRow in range(2): if (imageRow == 0): set = data; else: set = reconstruction; for i in range(data.shape[0]): img[(imageRow * data.shape[3]):((imageRow + 1) * data.shape[3]), (i * data.shape[2]):((i + 1) * data.shape[2])] = 255 * set[i, 0, :, :]; png.from_array(img, 'L').save(filename);
def GetColoursForGreedyPixels(): # Make a new searchable colour space colourSpace = SearchableColourSpace(colourBits, colourReuse) # Insert one pixel from the list to the image in a random spot - place neighbours in PixelQueue image = GreedyPixelList(width, height) RandR, RandG, RandB = (random.randint(0, 2**colourBits-1), random.randint(0, 2**colourBits-1), random.randint(0, 2**colourBits-1)) startx, starty = (randint(0,width-1),randint(0,height-1)) image[startx][starty] = (RandR, RandG, RandB, -1) image.UpdateNeighbours(startx,starty) colourSpace.FlagColourAsUsed(RandR, RandG, RandB) i = 1 for pixel in image.NextPixel(): NearbyColours = colourSpace.GetNearestNeighbours(pixel[0:3]) assert(NearbyColours is not None) if(len(NearbyColours) <= 0): print "aaarg! ", pixel.printTarget() png.from_array(image.FlatRows(), "RGB", {"height":height,"bitdepth":colourBits}).save(fileName+".png") raise Exception("Aaaerg!") BestMatch = None for CurrentColour in NearbyColours: if ( BestMatch is None ): BestMatch = CurrentColour if (GetHueDist(pixel[0:3], CurrentColour) < \ GetHueDist(pixel[0:3], BestMatch)): BestMatch = CurrentColour pixel[3] = -1 pixel[0:3] = BestMatch colourSpace.FlagColourAsUsed(RGB=BestMatch) image.UpdateNeighbours() i += 1 if (i%1000 == 0): print i, datetime.now()- StartTime if (i%imageInterval == 0): MakeImageThread = threading.Thread(target = MakeImage, args=(image, height, colourBits, fileName+"_"+str(i/imageInterval)+".png")) MakeImageThread.start() MakeImage(image, height, colourBits, fileName+".png")
def worker(tpl): it, fn = tpl data = load(fn) if len(data.shape) == 3: data = data[0,:,:] data = (data - fmin) / (fmax - fmin) if (rmin != None) and (rmax != None) and (cmin != None) and (cmax != None): data = data[rmin:rmax, cmin:cmax] shape = data.shape data = cmap(data, bytes=True)[:,:,:3].reshape((shape[0], shape[1] * 3)) png.from_array(data, 'RGB;8').save(('%s/out_%0'+str(fmtlen)+'d.png') % (tdir,it))
def save_image(path): image_list = [] for y in range(HEIGHT): current_row = [] for x in range(WIDTH): if (x, y) in image: colour = image[(x, y)] current_row += [clamp(colour[0]), clamp(colour[1]), clamp(colour[2]), 255] else: current_row += [0, 0, 0, 0] image_list.append(current_row) png.from_array(image_list, "RGBA").save(path)
def _Save(self, filename): img = self.drawWindow.drawControl.image data = list() for y in range(img.GetHeight()): line = array("B") for x in range(img.GetWidth()): line.append(img.GetRed(x, y)) line.append(img.GetGreen(x, y)) line.append(img.GetBlue(x, y)) line.append(img.GetAlpha(x, y)) data.append(line) png.from_array(data, "RGBA").save(filename)
def _repr_png_(self, _crop_box=None): """Hook for IPython Notebook See: http://ipython.org/ipython-doc/stable/config/integrating.html """ if _crop_box or self.trans: if not _crop_box: _crop_box = 0, 0, self.width, self.height left, up, right, low = _crop_box data = [l[left * 4:right * 4] for l in self.image_data[up:low]] out = BytesIO() png.from_array(data, 'RGBA').save(out) return out.getvalue() return self.data
def main(wb): wb.open() regs = wb.regs # # # print("dumping framebuffer memory...") dump = [] for n in range(DUMP_SIZE//(WORDS_PER_PACKET*4)): data = wb.read(SDRAM_BASE + n*WORDS_PER_PACKET*4, WORDS_PER_PACKET) for pixel in data: dump += extract_rgb(pixel) dump = [dump[x:x+LINE_SIZE] for x in range(0, len(dump), LINE_SIZE)] print("dumping to png file...") png.from_array(dump, "RGB").save("dump.png") # # # wb.close()
def data(lines): img = png.from_array(lines, 'RGB') buff.seek(0) writer.write(buff, img.rows) return buff.getvalue()
def Crop(self, left, top, width, height): """Returns a new PngBitmap that represents the specified sub-rect of this PngBitmap""" if (left < 0 or top < 0 or (left + width) > self.width or (top + height) > self.height): raise Exception('Invalid dimensions') img_data = [[0 for x in xrange(width * 4)] for x in xrange(height)] # Copy each pixel in the sub-rect for y in range(height): for x in range(width): c = self.GetPixelColor(x + left, y + top) offset = x * 4 img_data[y][offset] = c.r img_data[y][offset+1] = c.g img_data[y][offset+2] = c.b img_data[y][offset+3] = c.a # This particular method can only save to a file, so the result will be # written into an in-memory buffer and read back into a PngBitmap crop_img = png.from_array(img_data, mode='RGBA') output = cStringIO.StringIO() try: crop_img.save(output) crop_png = PngBitmap(output.getvalue()) finally: output.close() return crop_png
def testfromarrayIter(self): """Test writing from iterator""" i = itertools.islice(itertools.count(10), 20) i = [[x, x, x] for x in i] img = png.from_array(i, 'RGB;5', dict(height=20)) f = BytesIO() img.save(f)
def Crop(self, left, top, width, height): """Returns a new Bitmap that represents the specified sub-rect of this.""" if left < 0 or top < 0 or (left + width) > self.width or (top + height) > self.height: raise ValueError("Invalid dimensions") img_data = [[0 for x in xrange(width * 4)] for x in xrange(height)] # Copy each pixel in the sub-rect. # TODO(tonyg): Make this faster by avoiding the copy and artificially # restricting the dimensions. for y in range(height): for x in range(width): c = self.GetPixelColor(x + left, y + top) offset = x * 4 img_data[y][offset] = c.r img_data[y][offset + 1] = c.g img_data[y][offset + 2] = c.b img_data[y][offset + 3] = c.a # This particular method can only save to a file, so the result will be # written into an in-memory buffer and read back into a Bitmap crop_img = png.from_array(img_data, mode="RGBA") output = cStringIO.StringIO() try: crop_img.save(output) crop = Bitmap.FromPng(output.getvalue()) finally: output.close() return crop
def main(params) : name = params["name"] pixel = params["pixel_size"] dims = params["size"] - 2 colors = ( params["background_color"], (randint(0, 255), randint(0, 255), randint(0, 255)) ) matrix = lambda : [[colors[0]]] + [[choice(colors)] for i in range(dims)] + [[colors[0]]] matrizen = list() for i in range(dims // 2 + dims % 2) : matrizen.append(matrix()) for i in range(dims // 2)[::-1] : matrizen.append(matrizen[i]) matrizen.insert(0, [[colors[0]] for i in range(dims+2)]) matrizen.append([[colors[0]] for i in range(dims+2)]) array = numpy.concatenate(matrizen, axis=1) array = array.repeat(pixel, axis=0).repeat(pixel, axis=1) array = numpy.array( [[ val for triple in dim for val in triple] for dim in array] ) img = png.from_array(array, "RGB") img.info["bitdepth"] = 8 img.save(name)
def write_png(self, pngfile): print("pngfile {}".format(pngfile)) if self._finished is False: self._finish_pixel() self._finished = True if self.size > self.order: scale = 2 ** (self.size - self.order) height = int(self.height * scale) width = int(self.width * scale) hscale = height / self.height wscale = width / self.width image = png.from_array(([self._grid[int(y//hscale)][int(x//wscale)] for x in xrange(width)] for y in xrange(height)), 'L', info={'height': height}) else: image = png.from_array(self._grid, 'L') image.save(pngfile)
def testNumpyarray(self): """numpy array.""" numpy or self.skipTest("numpy is not available") pixels = numpy.array([[0,0x5555],[0x5555,0xaaaa]], numpy.uint16) img = png.from_array(pixels, 'L') img.save(BytesIO())
def apply_color(): image = open(args.original_file) r=png.Reader(file=image) imageArray = list(r.read()[2]) newImage = open(args.new_file,"wb") w=png.Writer(len(imageArray[0]),len(imageArray)) newArray = list() width = len(imageArray[0]) for y in range(len(imageArray)): newArray.append(list()) for x in range(width): color = imageArray[y][x] hsv = colorsys.rgb_to_hsv(color/255.0,color/255.0,color/255.0) rgb = colorsys.hsv_to_rgb(args.hue[0]/360.0,args.saturation[0]/100.0, hsv[2]*(1-colorValueRangeMin) + colorValueRangeMin) for i in range(3): newArray[y].append(rgb[i]*255) png.from_array(newArray,'RGB').save(newImage) return imageArray
def render(): global bitmap resized = [[0 for _ in range(3*Xdim)] for _ in range(Ydim)] for i in range(Xdim): for j in range(Ydim): resized[j][i*3 + 0] = bitmap[i][j][0] resized[j][i*3 + 1] = bitmap[i][j][1] resized[j][i*3 + 2] = bitmap[i][j][2] pic = png.from_array(resized, mode='RGB;8') return pic
def createPngFromBlockTuples(tupleList, levelSize, name='pngtest.png'): # where tupleList is a list of block position tuples, levelSize is a tuple of x,y level size width, height = levelSize pngList = [[0 for y in xrange(height)] for x in xrange(width)] for t in tupleList: # I could probably use list comprehensions here print str(t) x,y = t column = pngList[y] column[x] = 255 image = png.from_array(pngList, mode='L') # grayscale image.save(name)