def outputFiles(self, filename, attachLogo=False, logoText=None): rendered = self.getTarget().screenshot() if attachLogo: from java.awt.image import BufferedImage noaa = File(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logos/noaalogo2.png')) nws = File(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logos/nwslogo.png')) noaaImage = ImageIO.read(noaa) nwsImage = ImageIO.read(nws) height = rendered.getHeight() + noaaImage.getHeight() finalBuf = BufferedImage(rendered.getWidth(), height, BufferedImage.TYPE_INT_ARGB) graphics = finalBuf.createGraphics() graphics.drawImage(rendered, 0, 0, None) graphics.drawImage(noaaImage, 0, rendered.getHeight(), None) graphics.fillRect(noaaImage.getWidth(), rendered.getHeight(), rendered.getWidth() - noaaImage.getWidth() - nwsImage.getWidth(), rendered.getHeight()) if logoText is not None: from java.awt import Color graphics.setColor(Color.BLACK) graphics.setFont(self.getAWTFont(self.getTarget().getDefaultFont())) fm = graphics.getFontMetrics() textBounds = fm.getStringBounds(logoText, graphics) graphics.drawString(logoText, int((rendered.getWidth() - textBounds.getWidth()) / 2), \ int(rendered.getHeight() + (noaaImage.getHeight() / 2) + textBounds.getHeight() / 2)) graphics.drawImage(nwsImage, finalBuf.getWidth() - nwsImage.getWidth(), rendered.getHeight(), None) finalBuf.flush() self.outputImage(finalBuf, filename) else: self.outputImage(rendered, filename)
def test_parse_svgfile_and_convert_to_png_hat_q4(self): img_proc_dir = os.path.join(helpers.APP_PATH, "test", "res", "img_proc_png") input_svg_path = os.path.join(img_proc_dir, "input_hat.svg") assert os.path.exists(input_svg_path) rotation_x, rotation_y = 97, -51 expected_image_path = os.path.join( img_proc_dir, "expected_hat" + "_rotX_" + str(rotation_x) + "_rotY_" + str(rotation_y) + ".png") output_png_path = svgtopng.convert(input_svg_path, rotation_x, rotation_y) from javax.imageio import ImageIO from java.io import File bufferd_image = ImageIO.read(File(output_png_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() output_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] bufferd_image = ImageIO.read(File(expected_image_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() expected_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] for i in xrange(width): for j in xrange(height): exp_rgb_val = expected_image_matrix[i][j] result_rgb_val = output_image_matrix[i][j] assert exp_rgb_val == result_rgb_val
def test_parse_svgfile_and_convert_to_png_background(self): img_proc_dir = os.path.join(helpers.APP_PATH, "test", "res", "img_proc_png") input_svg_path = os.path.join(img_proc_dir, "input_background.svg") expected_image_path = os.path.join(img_proc_dir, "expected_background.png") assert os.path.exists(input_svg_path) rotation_x, rotation_y = 255, 180 output_png_path = svgtopng.convert(input_svg_path, rotation_x, rotation_y, ns_registry_lock) from javax.imageio import ImageIO from java.io import File bufferd_image = ImageIO.read(File(output_png_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() output_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] bufferd_image = ImageIO.read(File(expected_image_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() expected_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] for i in xrange(width): for j in xrange(height): exp_rgb_val = expected_image_matrix[i][j] result_rgb_val = output_image_matrix[i][j] assert exp_rgb_val == result_rgb_val
def outputFiles(self, filename, attachLogo=False, logoText=None): rendered = self.getTarget().screenshot() if attachLogo: from java.awt.image import BufferedImage from com.raytheon.uf.common.localization import PathManagerFactory noaa = 'pyViz/logos/noaalogo2.png' nws = 'pyViz/logos/nwslogo.png' pathMgr = PathManagerFactory.getPathManager() noaa = pathMgr.getStaticFile(noaa) nws = pathMgr.getStaticFile(nws) noaaImage = ImageIO.read(noaa) nwsImage = ImageIO.read(nws) height = rendered.getHeight() + noaaImage.getHeight() finalBuf = BufferedImage(rendered.getWidth(), height, BufferedImage.TYPE_INT_ARGB) graphics = finalBuf.createGraphics() graphics.drawImage(rendered, 0, 0, None) graphics.drawImage(noaaImage, 0, rendered.getHeight(), None) graphics.fillRect(noaaImage.getWidth(), rendered.getHeight(), rendered.getWidth() - noaaImage.getWidth() - nwsImage.getWidth(), rendered.getHeight()) if logoText is not None: from java.awt import Color from com.raytheon.uf.viz.core.font import FontAdapter graphics.setColor(Color.BLACK) graphics.setFont(FontAdapter.getAWTFont(self.getTarget().getDefaultFont())) fm = graphics.getFontMetrics() textBounds = fm.getStringBounds(logoText, graphics) graphics.drawString(logoText, int((rendered.getWidth() - textBounds.getWidth()) / 2), \ int(rendered.getHeight() + (noaaImage.getHeight() / 2) + textBounds.getHeight() / 2)) graphics.drawImage(nwsImage, finalBuf.getWidth() - nwsImage.getWidth(), rendered.getHeight(), None) finalBuf.flush() self.outputImage(finalBuf, filename) else: self.outputImage(rendered, filename)
def test_parse_svgfile_and_convert_to_png_antenna(self): img_proc_dir = os.path.join(helpers.APP_PATH, "test", "res", "img_proc_png") input_svg_path = os.path.join(img_proc_dir, "input_antenna.svg") expected_image_path = os.path.join(img_proc_dir, "expected_antenna.png") assert os.path.exists(input_svg_path) rotation_x, rotation_y = 53, 43 output_png_path = svgtopng.convert(input_svg_path, rotation_x, rotation_y) from javax.imageio import ImageIO from java.io import File bufferd_image = ImageIO.read(File(output_png_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() output_image_matrix = [[bufferd_image.getRGB(i, j) for j in xrange(height)] for i in xrange(width)] bufferd_image = ImageIO.read(File(expected_image_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() expected_image_matrix = [[bufferd_image.getRGB(i, j) for j in xrange(height)] for i in xrange(width)] for i in xrange(width): for j in xrange(height): exp_rgb_val = expected_image_matrix[i][j] result_rgb_val = output_image_matrix[i][j] assert exp_rgb_val == result_rgb_val
def __init__(self,hostname): self.hostname=hostname JPanel.__init__(self,BorderLayout()) self.cbActionListener=foo2(self) #imglist=os.listdir('./img') #try:imglist.remove('.svn') #except:pass imglist=['01-CircleOfFifths.gif','Fifths.png','circle-o-fifths.jpg','Circle_Of_Fifths.gif','Keywheel.gif','circle-of-fifths.gif','ColorFifths.jpg','cof.gif'] self.cb=JComboBox(imglist,actionListener=self.cbActionListener)# #self.cb.addItemListener(self.cbCB) tb=JPanel() tb.setLayout(FlowLayout(FlowLayout.CENTER)) tb.add(self.cb) self.add(tb,'Center') self.img=None if hostname[0:7]=='http://': self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+imglist[0])) else: self.img=ImageIO.read(File(self.hostname+'img/'+imglist[0])) icon=ImageIcon(self.img) self.label=JLabel(icon) self.add(self.label,'North')
def getimage(self) : if not os.path.exists('tools/image.png') : imagedata = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ\nbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdp\nbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6\neD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEz\nNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJo\ndHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlw\ndGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAv\nIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RS\nZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpD\ncmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNl\nSUQ9InhtcC5paWQ6MzZDNTFCOUZGNUQ5MTFERkE0Mzk4NUE5OTMzRTQwNzkiIHhtcE1NOkRvY3Vt\nZW50SUQ9InhtcC5kaWQ6MzZDNTFCQTBGNUQ5MTFERkE0Mzk4NUE5OTMzRTQwNzkiPiA8eG1wTU06\nRGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDozNkM1MUI5REY1RDkxMURGQTQz\nOTg1QTk5MzNFNDA3OSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDozNkM1MUI5RUY1RDkxMURG\nQTQzOTg1QTk5MzNFNDA3OSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1w\nbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pms/CZAAAAECSURBVHjaYtRe+JiBloCJgcZg1IIhZYHV\ntzNARKoFLESqY/3/p+DNHCDjtKzBb0YW6vvA9/Numd/Pgcj/007qBxHfvy9p75ZC2CnvlwO5VLYg\n7d0Svr+foZb9/QzkUtMC1Z/3A1CDBcgFClLNgqK3s5j+/0PR8/8fUJA6Fth+PaX//RqmOFAQKEWp\nBcCkmft2Hi5ZoBRQAUUWRHzcCEyXuGSBUkAF5Fsg+udtwvtV+DUDFQCVkWlB9ruFnP9+4NcMVABU\nRo4FwFTo9vkgMXEIVIY/yWIvVTR+3dnI505kQgQqvs2uSJoF/nltxOdVVQaGzfNdRyucUQtGLRi1\ngAIAEGAAimxsT0J9RpkAAAAASUVORK5CYII=\n' actual_image = base64.b64decode(imagedata) from java.io import ByteArrayInputStream stream = ByteArrayInputStream(actual_image) self._image = ImageIO.read(stream); else : self._image = ImageIO.read(File('tools/image.png'))
def updateProduct(self, *args): try: value = self.lstProducts.getSelectedValue() except: return if value == None: return #try: if True: width = 150 height = 150 #gvSIGPath = Utilities.TEMPDIRECTORYPATH gvSIGPath = "/home/osc/temp" outputPath = os.path.join( gvSIGPath, value.getName() + "_%sx%s.jpg" % (width, height)) #Utilities.TEMPDIRECTORYPATH if os.path.exists(outputPath) == False: url = value.getPreviewLink() f = download(url) total_size = int(f.headers["Content-Length"]) MB_size = round(total_size / 1048576, 2) block_size = 1024 * 1024 outputPathFull = gvSIGPath + value.getName() + ".jpg" with open(outputPath, "wb") as file: while True: block = f.read(block_size) dSize = round( int(os.stat(outputPath).st_size) / 1048576, 2) print "(" + str(dSize) + "/" + str( MB_size) + " MB) " + url + "Downloading" if not block: break file.write(block) img = ImageIO.read(outputPathFull) tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH) resized = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) g2d = resized.createGraphics() g2d.drawImage(tmp, 0, 0, None) g2d.dispose() ImageIO.write(resized, "jpg", outputPath) else: print "already downloaded" myPicture = ImageIcon(ImageIO.read(File(outputPath))) self.txtInfo.setText(value.getInfoString()) self.tabInfo.updateUI() self.lstProducts.updateUI() self.lstProducts.revalidate() self.lstProducts.repaint() #except: # myPicture = ImageIcon() self.lblPreview.setIcon(myPicture)
def cbCB(self,e): try: item=self.cb.getSelectedItem() if DEBUG:print item if self.hostname[0:7]=='http://': self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+item)) else: self.img=ImageIO.read(File(self.hostname+'img/'+item)) if DEBUG:print self.img icon=ImageIcon(self.img) self.label.setIcon(icon) except Exception,e: if DEBUG:print e
def read(self, filename): """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels.""" # JEM working directory fix (see above) filename = fixWorkingDirForJEM( filename ) # does nothing if not in JEM # *** #print "fixWorkingDirForJEM( filename ) =", filename file = File(filename) # read file from current directory self.image = ImageIO.read(file) self.width = self.image.getWidth(None) self.height = self.image.getHeight(None) pixels = [] # initialize list of pixels # load pixels from image for row in range(self.height): pixels.append( [] ) # add another empty row for col in range(self.width): # now, populate row with pixels color = Color(self.image.getRGB(col, row)) # get pixel's color RGBlist = [color.getRed(), color.getGreen(), color.getBlue()] # create list of RGB values (0-255) pixels[-1].append( RGBlist ) # add a pixel as (R, G, B) values (0-255, each) # now, pixels have been loaded from image file, so create an image self.setPixels(pixels)
def read(self, filename): """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels.""" # JEM working directory fix (see above) filename = fixWorkingDirForJEM(filename) # does nothing if not in JEM # *** #print "fixWorkingDirForJEM( filename ) =", filename file = File(filename) # read file from current directory self.image = ImageIO.read(file) self.width = self.image.getWidth(None) self.height = self.image.getHeight(None) pixels = [] # initialize list of pixels # load pixels from image for row in range(self.height): pixels.append([]) # add another empty row for col in range(self.width): # now, populate row with pixels color = Color(self.image.getRGB(col, row)) # get pixel's color RGBlist = [color.getRed(), color.getGreen(), color.getBlue() ] # create list of RGB values (0-255) pixels[-1].append( RGBlist) # add a pixel as (R, G, B) values (0-255, each) # now, pixels have been loaded from image file, so create an image self.setPixels(pixels)
def _read_image(self,fp): if sys.platform[0:4] == 'java': from javax.imageio import ImageIO return ImageIO.read(fp) else: import PIL.Image return PIL.Image.open(fp)
def gui_open(path): label = JLabel(ImageIcon(ImageIO.read(File(URL(path).getFile())))) frame = JFrame() frame.getContentPane().add(label) frame.pack() frame.setLocation(200, 200) frame.setVisible(True)
def readable_values(im_paths): from os.path import basename for im_pth in im_paths: im = ImageIO.read(File(im_pth)) print "" print "-" * 120 print "" print "IMAGE: %s" % basename(im_pth) for histoval in test_color_layout(im): print histoval for histoval in test_edge_histogram(im): print histoval for histoval in test_PHOG(im): print histoval for histoval in test_opponent_histogram(im): print histoval #for histoval in test_JCD(im): # print histoval print ""
def _read_image(self, fp): if sys.platform[0:4] == "java": from javax.imageio import ImageIO return ImageIO.read(fp) else: return Image.open(fp)
def readImg(filename): from java.io import File from javax.imageio import ImageIO import sys, os scriptDir = os.path.dirname(sys.argv[0]) return ImageIO.read( File(os.path.join(scriptDir, "stateDetectionImages", filename)))
def loadImage(filepath): fp = open(filepath, 'r') image = ImageIO.read(fp) fp.close() return image
def json_encoded_values(im_paths): import simplejson as json list_of_dicts = [] list_of_names = ('string', 'base64', 'hash') for im_pth in im_paths: im = ImageIO.read(File(im_pth)) list_of_dicts.append(dict( color_layout=dict( zip(list_of_names, test_color_layout(im, silence=True))), edge_histogram=dict( zip(list_of_names, test_edge_histogram(im, silence=True))), phog=dict( zip(list_of_names, test_PHOG(im, silence=True))), opponent_histogram=dict( zip(list_of_names, test_opponent_histogram(im, silence=True))), # jcd=dict( # zip(list_of_names, # test_JCD(im, silence=True))), )) print json.dumps(list_of_dicts, indent=4)
def getColorFormImage(fn): f = jf.File(fn) img = IIO.read(f) x = img.getWidth()/2 y = img.getHeight()/2 #print "gk "+str(x) +str(y) return JColor(img.getRGB(x,y))
def save_mediafiles_into_catroid_directory_structure(): def update_md5_hash(current_md5_name, file_path_for_update): resource_maps = list(sb2_project.project_code.resource_dicts_of_md5_name(current_md5_name)) md5_name = common.md5_hash(file_path_for_update) + os.path.splitext(file_path_for_update)[1] for resource_map in resource_maps: if sb2keys.COSTUME_MD5 in resource_map: resource_map[sb2keys.COSTUME_MD5] = md5_name elif sb2keys.SOUND_MD5 in resource_map: resource_map[sb2keys.SOUND_MD5] = md5_name else: assert False, "Unknown dict: {}".resource_map return md5_name for md5_name, src_path in sb2_project.md5_to_resource_path_map.iteritems(): file_ext = os.path.splitext(md5_name)[1].lower() converted_file = False # TODO; extract method if file_ext in {".png", ".svg", ".jpg", ".gif"}: target_dir = images_path # # WORKAROUNF: penLayerMD5 file # if not resource_maps: # continue if file_ext == ".svg": # converting svg to png -> new md5 and filename src_path = svgtopng.convert(src_path) converted_file = True elif md5_name in sb2_project.background_md5_names: # resize background if not matching the default resolution imageFile = File(src_path) pngImage = ImageIO.read(imageFile) if pngImage.getWidth() > sb2.STAGE_WIDTH_IN_PIXELS or pngImage.getHeight() > sb2.STAGE_HEIGHT_IN_PIXELS: resizedImage = imageresizer.resize_png(pngImage, sb2.STAGE_WIDTH_IN_PIXELS, sb2.STAGE_HEIGHT_IN_PIXELS) # FIXME src_path = src_path.replace(".png", "resized.png") ImageIO.write(resizedImage, "png", File(src_path)) converted_file = True elif file_ext in {".wav", ".mp3"}: target_dir = sounds_path if file_ext == ".wav": if not wavconverter.is_android_compatible_wav(src_path): temp_path = src_path.replace(".wav", "converted.wav") wavconverter.convert_to_android_compatible_wav(src_path, temp_path) src_path = temp_path converted_file = True else: assert file_ext in {".json"}, md5_name continue assert os.path.exists(src_path), "Not existing: {}".format(src_path) if converted_file: md5_name = update_md5_hash(md5_name, src_path) # if file is used multiple times: single md5, multiple filenames for catroid_file_name in _convert_resource_name(sb2_project, md5_name): shutil.copyfile(src_path, os.path.join(target_dir, catroid_file_name)) if converted_file: os.remove(src_path)
def average_hash_and_sizes(self): height = 0 width = 0 if isJython(): image = ImageIO.read(File(self.image_path)) height = image.getHeight() width = image.getWidth() newImage = BufferedImage(self.hash_size, self.hash_size, BufferedImage.TYPE_INT_ARGB) g = newImage.createGraphics() g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawImage(image, 0, 0, self.hash_size, self.hash_size, None) g.dispose() allchannelpixels = [[], [], [], []] for i in range(self.hash_size): for j in range(self.hash_size): pixel = int(newImage.getRGB(i, j)) allchannelpixels[0].append((pixel >> 16) & 0xFF) allchannelpixels[1].append((pixel >> 8) & 0xFF) allchannelpixels[2].append((pixel) & 0xFF) allchannelpixels[3].append((pixel >> 24) & 0xFF) elif isIronPython(): srcImage = Bitmap(self.image_path) height = srcImage.Height width = srcImage.Width newImage = Bitmap(self.hash_size, self.hash_size) gr = Graphics.FromImage(newImage) gr.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias gr.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic gr.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality gr.DrawImage(srcImage, Rectangle(0, 0, self.hash_size, self.hash_size)) allchannelpixels = [[], [], [], []] for i in range(self.hash_size): for j in range(self.hash_size): pixel = newImage.GetPixel(i, j) allchannelpixels[0].append(int(pixel.R)) allchannelpixels[1].append(int(pixel.G)) allchannelpixels[2].append(int(pixel.B)) allchannelpixels[3].append(int(pixel.A)) else: self.image = Image.open(self.image_path) width, height = self.image.size image = self.image.resize((self.hash_size, self.hash_size), Image.ANTIALIAS) # image.show() allchannelpixels = [ list(channel.getdata()) for channel in image.split() ] bits = [] for pixels in allchannelpixels: bits.append(self.getBitString(pixels)) return bits, width, height
def loadSS(self, imgPath): image = ImageIO.read(File(imgPath)) if image.getWidth() <= 550 and image.getHeight() <= 400: self.firstPic.setIcon(ImageIcon(image)) self.firstPic.setSize(image.getWidth(),image.getHeight()) else: self.firstPic.setIcon(ImageIcon(self.resize(image,550, 400))) self.firstPic.setSize(550,400)
def mouseClicked(self,s,g) : f = self.get_image_file() #TODO: figure out how to extract the image #and encode into a string if f: image = ImageIO.read(f) self.sendImage = ImageData(s.x, s.y, image) return ''
def jpg2bmp(src): # load jpg b = bmp_name(src) f = File(src) image = ImageIO.read(f) output = File(b) ImageIO.write(image,"bmp",output)
def _read_image(self, fp): if sys.platform[0:4] == 'java': from javax.imageio import ImageIO from java.io import ByteArrayInputStream input_stream = ByteArrayInputStream(fp.read()) return ImageIO.read(input_stream) elif PILImage: return PILImage.open(fp)
def __init__(self, actions, mapname, colormap, name="PlaceCellEnvironment", imgsize=(1.0, 1.0), dx=0.01, placedev=0.1, num_places=None): """Initialize environment variables. :param actions: actions available to the system :type actions: list of tuples (action_name,action_vector) :param mapname: name of file describing environment map :param colormap: dict mapping pixel colours to labels :param name: name for environment :param imgsize: width of space represented by the map image :param dx: distance agent moves each timestep :param placedev: standard deviation of gaussian place cell activations :param num_places: number of placecells to use (if None it will attempt to fill the space) """ EnvironmentTemplate.__init__(self, name, 2, actions) # parameters self.colormap = colormap self.rewardamount = 0 # number of timesteps spent in reward # number of timesteps to spend in reward before agent is reset # note: convenient to express this as time_in_reward / dt self.rewardresetamount = 0.6 / 0.001 self.num_actions = len(actions) self.imgsize = [float(x) for x in imgsize] self.dx = dx self.placedev = placedev self.num_places = num_places self.optimal_move = None self.defaultreward = -0.075 # load environment self.map = ImageIO.read(File(HRLutils.datafile(mapname))) # generate place cells self.gen_placecells(min_spread=1.0 * placedev) # initial conditions self.state = self.random_location(avoid=["wall", "target"]) self.place_activations = [0 for _ in self.placecells] self.create_origin("place", lambda: self.place_activations) # note: making the value small, so that the noise node will give us # some random exploration as well self.create_origin( "optimal_move", lambda: [0.1 if self.optimal_move == a[0] else 0.0 for a in self.actions])
def initUI(self): self.panel = JPanel(size=(50,50)) self.panel.setLayout(FlowLayout( )) self.panel.setToolTipText("GPU Demo") #TODO- change this so that it deletes itself when text is entered self.textfield1 = JTextField('Smoothing Parameter',15) self.panel.add(self.textfield1) joclButton = JButton("JOCL",actionPerformed=self.onJocl) joclButton.setBounds(100, 500, 100, 30) joclButton.setToolTipText("JOCL Button") self.panel.add(joclButton) javaButton = JButton("Java",actionPerformed=self.onJava) javaButton.setBounds(100, 500, 100, 30) javaButton.setToolTipText("Java Button") self.panel.add(javaButton) qButton = JButton("Quit", actionPerformed=self.onQuit) qButton.setBounds(200, 500, 80, 30) qButton.setToolTipText("Quit Button") self.panel.add(qButton) newImage = ImageIO.read(io.File(getDataDir() + "input.png")) resizedImage = newImage.getScaledInstance(600, 600,10) newIcon = ImageIcon(resizedImage) label1 = JLabel("Input Image",newIcon, JLabel.CENTER) label1.setVerticalTextPosition(JLabel.TOP) label1.setHorizontalTextPosition(JLabel.RIGHT) label1.setSize(10,10) label1.setBackground(Color.orange) self.panel.add(label1) self.getContentPane().add(self.panel) self.clockLabel = JLabel() self.clockLabel.setSize(1,1) self.clockLabel.setBackground(Color.orange) self.clockLabel.setVerticalTextPosition(JLabel.BOTTOM) self.clockLabel.setHorizontalTextPosition(JLabel.LEFT) myClockFont = Font("Serif", Font.PLAIN, 50) self.clockLabel.setFont(myClockFont) self.panel.add(self.clockLabel) self.setTitle("Structure-oriented smoothing OpenCL Demo") self.setSize(1200, 700) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True)
def create_icon(self, path): try: im = ImageIO.read(File(path)) except: raise im = im.getScaledInstance(32, 32, Image.SCALE_SMOOTH) icon = ImageIcon(im) return icon
def load(self, img_file, namehint=None): """ Load image from file as a java.awt.image.BufferedImage. The img_file can be a filename or file-like object. Return the bufferedimage as a Surface. """ if isinstance(img_file, str): try: f = env.japplet.getClass().getResource(img_file.replace('\\','/')) if not f: raise except: f = File(img_file) bimage = ImageIO.read(f) else: bimage = ImageIO.read(ByteArrayInputStream(img_file.getvalue())) img_file.close() surf = Surface(bimage) return surf
def next(self): image_file_name = self.iterator.next() #Find example label label = image_file_name[0:image_file_name.index('_')] #Get the image as an image buffer image_file = File(dir_path, image_file_name) image_is = FileInputStream(image_file) buffered_image = ImageIO.read(image_is) #Return label and image tuple return (label, buffered_image)
def initUI(self): self.panel = JPanel(size=(50, 50)) self.panel.setLayout(FlowLayout()) self.panel.setToolTipText("GPU Demo") self.textfield1 = JTextField('Smoothing Parameter', 15) self.panel.add(self.textfield1) joclButton = JButton("JOCL", actionPerformed=self.onJocl) joclButton.setBounds(100, 500, 100, 30) joclButton.setToolTipText("JOCL Button") self.panel.add(joclButton) javaButton = JButton("Java", actionPerformed=self.onJava) javaButton.setBounds(100, 500, 100, 30) javaButton.setToolTipText("Java Button") self.panel.add(javaButton) qButton = JButton("Quit", actionPerformed=self.onQuit) qButton.setBounds(200, 500, 80, 30) qButton.setToolTipText("Quit Button") self.panel.add(qButton) newImage = ImageIO.read(io.File("input.png")) resizedImage = newImage.getScaledInstance(600, 600, 10) newIcon = ImageIcon(resizedImage) label1 = JLabel("Input Image", newIcon, JLabel.CENTER) label1.setVerticalTextPosition(JLabel.TOP) label1.setHorizontalTextPosition(JLabel.RIGHT) label1.setSize(10, 10) label1.setBackground(Color.orange) self.panel.add(label1) self.getContentPane().add(self.panel) self.clockLabel = JLabel() self.clockLabel.setSize(1, 1) self.clockLabel.setBackground(Color.orange) self.clockLabel.setVerticalTextPosition(JLabel.BOTTOM) self.clockLabel.setHorizontalTextPosition(JLabel.LEFT) myClockFont = Font("Serif", Font.PLAIN, 50) self.clockLabel.setFont(myClockFont) self.panel.add(self.clockLabel) self.setTitle("GPU Demo") self.setSize(1200, 600) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True)
def load(self, img_file, namehint=None): """ Load image from file as a java.awt.image.BufferedImage. The img_file can be a filename or file-like object. Return the bufferedimage as a Surface. """ if isinstance(img_file, str): try: f = env.japplet.getClass().getResource( img_file.replace('\\', '/')) if not f: raise except: f = File(img_file) bimage = ImageIO.read(f) else: bimage = ImageIO.read(ByteArrayInputStream(img_file.getvalue())) img_file.close() surf = Surface(bimage) return surf
def animated(images, file=None, delay=300, loop=False): """ Generates an anmiated GIF. The *images* parameter is a sequence of objects that can be read as GIF images, such as an array of bytes. The *file* parameter specifies the file to generate. When omitted the resulting animated GIF is returned from this function as an array byte. The *delay* specifies the frame rate in milliseconds. The *loop* parameter specifies whether the animated GIF should loop continously. """ from com.sun.media.imageioimpl.plugins.gif import GIFImageWriter from com.sun.media.imageioimpl.plugins.gif import GIFImageWriterSpi out = ByteArrayOutputStream() if file is None else util.toFile(file) ios = ImageIO.createImageOutputStream(out) w = GIFImageWriter(GIFImageWriterSpi()) w.setOutput(ios) w.prepareWriteSequence(None) wp = w.getDefaultWriteParam() wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) wp.setCompressionType('LZW') wp.setCompressionQuality(0.75) for img in images: iis = ImageIO.createImageInputStream(util.toInputStream(img)) ri = ImageIO.read(iis) md = w.getDefaultImageMetadata(ImageTypeSpecifier(ri), wp) t = IIOMetadataTree(md) t.set('GraphicControlExtension', delayTime=delay / 10) if loop is True: n = t.set('ApplicationExtensions', 'ApplicationExtension', applicationID='NETSCAPE', authenticationCode='2.0') n.setUserObject(jarray.array([0x1, 0, 0], 'b')) t.commit() w.writeToSequence(IIOImage(ri, None, md), wp) w.endWriteSequence() ios.flush() ios.close() if file is None: return out.toByteArray()
def test_bmp(): from javax.imageio import ImageIO from java.io import File img = ImageIO.read(File(HRLutils.datafile("contextmap.bmp"))) colours = [int(val) for val in img.getRGB(0, 0, img.getWidth(), img.getHeight(), None, 0, img.getWidth())] unique_colours = [] for c in colours: if c not in unique_colours: unique_colours += [c] print unique_colours
def enlargeimage(self,image,imagewidth,imageheight): imageFile = open(image); ###j make image bigger for easier reading i = ImageIO.read(imageFile) largeimage = i.getScaledInstance(imagewidth, imageheight, awt.Image.SCALE_SMOOTH) bImage = awt.image.BufferedImage(largeimage.getWidth(),largeimage.getHeight(),awt.image.BufferedImage.TYPE_INT_ARGB) g = bImage.createGraphics() g.drawImage(largeimage,0,0,None) g.dispose() outputfile = File(image) ImageIO.write(bImage, "png", outputfile) return re.sub("[^a-zA-Z0-9\.\- ]","", Image.text(image))
def __init__(self, actions, mapname, colormap, name="PlaceCellEnvironment", imgsize=(1.0, 1.0), dx=0.01, placedev=0.1, num_places=None): """Initialize environment variables. :param actions: actions available to the system :type actions: list of tuples (action_name,action_vector) :param mapname: name of file describing environment map :param colormap: dict mapping pixel colours to labels :param name: name for environment :param imgsize: width of space represented by the map image :param dx: distance agent moves each timestep :param placedev: standard deviation of gaussian place cell activations :param num_places: number of placecells to use (if None it will attempt to fill the space) """ EnvironmentTemplate.__init__(self, name, 2, actions) # parameters self.colormap = colormap self.rewardamount = 0 # number of timesteps spent in reward # number of timesteps to spend in reward before agent is reset # note: convenient to express this as time_in_reward / dt self.rewardresetamount = 0.6 / 0.001 self.num_actions = len(actions) self.imgsize = [float(x) for x in imgsize] self.dx = dx self.placedev = placedev self.num_places = num_places self.optimal_move = None self.defaultreward = -0.075 # load environment self.map = ImageIO.read(File(HRLutils.datafile(mapname))) # generate place cells self.gen_placecells(min_spread=1.0 * placedev) # initial conditions self.state = self.random_location(avoid=["wall", "target"]) self.place_activations = [0 for _ in self.placecells] self.create_origin("place", lambda: self.place_activations) # note: making the value small, so that the noise node will give us # some random exploration as well self.create_origin("optimal_move", lambda: [0.1 if self.optimal_move == a[0] else 0.0 for a in self.actions])
def cook(foto, sg): f = File(abspath(foto)) bi = ImageIO.read(f) raster = bi.raster w = raster.width h = raster.height seg = sg all = [] for i in xrange(0, w, seg): for j in xrange(0, h, seg): c = bi.raster.getPixel(i, j, [0.0, 0.0, 0.0]) all.append(Point(i, j)) all.append(c[0]) return all
def load(self, img_file, namehint=None): """ Load image from file as a java.awt.image.BufferedImage. Return the bufferedimage as a Surface. """ try: f = env.japplet.class.getResource(img_file.replace('\\','/')) #java uses /, not os.path Windows \ if not f: raise except: f = File(img_file) #make path os independent bimage = ImageIO.read(f) surf = Surface(bimage) return surf
def create_icon(self, path): # try : # im = ImageIO.read(File(path)) # im_url = self.getClass().getResource(path) # im = ImageIO.read(im_url) ins = self.getClass().getResourceAsStream(path) # reader = BufferedReader(InputStreamReader(is)) im = ImageIO.read(ins) # except : # raise im = im.getScaledInstance(32, 32, Image.SCALE_SMOOTH) icon = ImageIcon(im) return icon
def animated(images, file=None, delay=300, loop=False): """ Generates an anmiated GIF. The *images* parameter is a sequence of objects that can be read as GIF images, such as an array of bytes. The *file* parameter specifies the file to generate. When omitted the resulting animated GIF is returned from this function as an array byte. The *delay* specifies the frame rate in milliseconds. The *loop* parameter specifies whether the animated GIF should loop continously. """ from com.sun.media.imageioimpl.plugins.gif import GIFImageWriter from com.sun.media.imageioimpl.plugins.gif import GIFImageWriterSpi out = ByteArrayOutputStream() if file is None else util.toFile(file) ios = ImageIO.createImageOutputStream(out) w = GIFImageWriter(GIFImageWriterSpi()) w.setOutput(ios) w.prepareWriteSequence(None) wp = w.getDefaultWriteParam() wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) wp.setCompressionType('LZW') wp.setCompressionQuality(0.75) for img in images: iis = ImageIO.createImageInputStream(util.toInputStream(img)) ri = ImageIO.read(iis) md = w.getDefaultImageMetadata(ImageTypeSpecifier(ri),wp) t = IIOMetadataTree(md) t.set('GraphicControlExtension', delayTime=delay/10) if loop is True: n = t.set('ApplicationExtensions', 'ApplicationExtension', applicationID='NETSCAPE', authenticationCode='2.0') n.setUserObject(jarray.array([0x1,0, 0], 'b')) t.commit() w.writeToSequence(IIOImage(ri, None, md), wp) w.endWriteSequence() ios.flush() ios.close() if file is None: return out.toByteArray()
def __init__(self,hostname,img_dir,img_fname,duration,xc,yc): #print hostname,img_dir,img_fname,duration,xc,yc self.hostname=hostname self.img_dir=img_dir self.img_fname=img_fname self.amrest=False self.ly='' if False:pass elif img_fname=='r1.png': self.amrest=True self.ly='r' elif img_fname=='r2.png': self.amrest=True self.ly='r' elif img_fname=='r4.png': self.amrest=True self.ly='r' elif img_fname=='r8.png': self.amrest=True self.ly='r' if hostname[0:7]=='http://': self.img=ImageIO.read(URL(hostname+img_dir+img_fname)) else: self.img=ImageIO.read(File(hostname+img_dir+img_fname)) self.duration=duration self.xc=xc self.yc=yc self.w=self.img.getWidth() self.h=self.img.getHeight() self.w2=self.w/2 self.h2=self.h/2 self.x=self.xc-self.w/2 self.y=self.yc-self.h/2
def get_image_size(image): path = image["path"] try: from javax.imageio import ImageIO from java.io import File img = ImageIO.read(File(path)) width = img.getWidth() height = img.getHeight() except ImportError: from PIL import Image as PILImage img = PILImage.open(path) width, height = img.size image["custom_css"] += "height:%(height)spx;width:%(width)spx;" % {"width": width, "height": height}
def loadImage(path, classloader=None): """Loads an image resource as java.awt.Image from anywhere on the class path. Supported image types are JPEG, PNG and GIF, and possibly others if you have installed any extensions to the ImageIO system (such as `Java Advanced Imaging <http://java.sun.com/javase/technologies/desktop/media/jai/>`_). :param path: path to the resource (separate elements with '/') :param classloader: class loader to use for loading the resource :rtype: :class:`java.awt.Image` """ from javax.imageio import ImageIO stream = getResourceAsStream(path, classloader) return ImageIO.read(stream)
def test_bmp(): from javax.imageio import ImageIO from java.io import File img = ImageIO.read(File(HRLutils.datafile("contextmap.bmp"))) colours = [ int(val) for val in img.getRGB(0, 0, img.getWidth(), img.getHeight(), None, 0, img.getWidth()) ] unique_colours = [] for c in colours: if c not in unique_colours: unique_colours += [c] print unique_colours
def buildHTML(node): for child in node.findAllDepthFirst(): flink = None if child.link.text is not None: flink = child.link.text if child.text != SEPERATOR: child.setDetailsText("") child.setHideDetails(True) if flink is not None: ext = [".PNG", ".png", ".JPG", ".jpg", ".jpeg"] if flink.endswith(tuple(ext)): img = ImageIO.read(URL("file:" + flink)) mywidth = 400 wpercent = (mywidth / float(img.getWidth())) hsize = int((float(img.getHeight()) * float(wpercent))) child.setDetailsText("<html><body><p><img src=" + flink + " width=" + str(mywidth) + " height=" + str(hsize) + "></p></body></html>") child.parent.folded = True
def resize_png(self, path_in, path_out, bitmapResolution): import java.awt.image.BufferedImage import java.io.File import java.io.IOException input = java.io.File(path_in) image = ImageIO.read(input) from math import ceil new_height = int(ceil(image.getHeight() / float(bitmapResolution))) new_height = new_height if new_height > 2 else 2 new_width = int(ceil(image.getWidth() / float(bitmapResolution))) new_width = new_width if new_width > 2 else 2 def resize(img, height, width): tmp = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH) resized = java.awt.image.BufferedImage( width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB) g2d = resized.createGraphics() g2d.drawImage(tmp, 0, 0, None) g2d.dispose() empty = True for x in range(new_width): for y in range(new_height): alpha = (resized.getRGB(x, y) >> 24) & 0xff if alpha > 0: empty = False break if not empty: break if empty: argb = (80 << 24) | (0x00FF00) resized.setRGB(0, 0, argb) resized.setRGB(0, 1, argb) resized.setRGB(1, 1, argb) resized.setRGB(1, 0, argb) return resized resized = resize(image, new_height, new_width) output = java.io.File(path_out) ImageIO.write(resized, "png", output) return path_out
def __init__(self, fileName): if not haveImages: warnOnce('Imaging Library not available, unable to import bitmaps') return #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileName self._image = None self._width = None self._height = None self._transparent = None self._data = None self.fp = open_for_read(fileName,'b') #detect which library we are using and open the image if sys.platform[0:4] == 'java': from javax.imageio import ImageIO self._image = ImageIO.read(self.fp) else: import PIL.Image self._image = PIL.Image.open(self.fp)
def getimage(f): img = ImageIO.read(File(f)) print img.getRGB(100,100) w = img.getWidth() h = img.getHeight() size = max(w,h) def fn(p): #staging i = int(((p.x+1.0)*w)/2.0) j = int(((p.y+1.0)*w)/2.0) if i < w and j < h and i >= 0 and j >= 0: rgb = img.getRGB(i,j) r = (rgb >> 16) & 0xFF g = (rgb >> 8) & 0xFF b = rgb & 0xFF color = C(r/255.0, g/255.0, b/255.0) return color else: return C(0,0,0,0) return fn
def __init__(self, fileName): if isinstance(fileName,ImageReader): self.__dict__ = fileName.__dict__ #borgize return if not haveImages: raise RuntimeError('Imaging Library not available, unable to import bitmaps') #start wih lots of null private fields, to be populated by #the relevant engine. self.fileName = fileName self._image = None self._width = None self._height = None self._transparent = None self._data = None if _isPILImage(fileName): self._image = fileName self.fp = fileName.fp try: self.fileName = self._image.fileName except AttributeError: self.fileName = 'PILIMAGE_%d' % id(self) else: try: self.fp = open_for_read(fileName,'b') #detect which library we are using and open the image if sys.platform[0:4] == 'java': from javax.imageio import ImageIO self._image = ImageIO.read(self.fp) else: import PIL.Image self._image = PIL.Image.open(self.fp) if self._image=='JPEG': self.jpeg_fh = self._jpeg_fp except: et,ev,tb = sys.exc_info() if hasattr(ev,'args'): a = str(ev.args[-1])+(' fileName='+fileName) ev.args= ev.args[:-1]+(a,) raise et,ev,tb else: raise
def load(self, img_file, namehint=None): """ Load image from file as a java.awt.image.BufferedImage. Return the bufferedimage as a Surface. """ try: try: f = env.japplet.class.getResource(img_file.replace('\\','/')) #java uses /, not os.path Windows \ if not f: raise except: cload = ClassLoader.getSystemClassLoader() f = cload.getResourceAsStream(img_file.replace('\\','/')) print "fe" except: f = File(img_file) bimage = ImageIO.read(f) surf = Surface(bimage) return surf
def insert_barcode_into_footer(self, builder, section, pageId, footerType): # Move to the footer type in the specific section. builder.moveToSection(section.getDocument().indexOf(section)) builder.moveToHeaderFooter(footerType) # Insert the barcode, then move to the next line and insert the ID # along with the page number. # Use pageId if you need to insert a different barcode on each page. 0 # = First page, 1 = Second page etc. builder.insertImage(ImageIO.read(File(self.dataDir + "barcode.png"))) builder.writeln() builder.write("1234567890") builder.insertField("PAGE") # Create a right aligned tab at the right margin. tabPos = section.getPageSetup().getPageWidth() - section.getPageSetup().getRightMargin() - section.getPageSetup().getLeftMargin() builder.getCurrentParagraph().getParagraphFormat().getTabStops().add(TabStop(tabPos, TabAlignment.RIGHT, TabLeader.NONE)) # Move to the right hand side of the page and insert the page and page total. builder.write(ControlChar.TAB) builder.insertField("PAGE") builder.write(" of ") builder.insertField("NUMPAGES")
def initUI(self): panel = JPanel(size=(50,50)) panel.setLayout(BorderLayout( )) panel.setToolTipText("A Panel container") joclButton = JButton("JOCL", actionPerformed=self.onJOCL) joclButton.setBounds(100, 500, 100, 30) joclButton.setToolTipText("JOCL Button") panel.add(joclButton) qButton = JButton("Quit", actionPerformed=self.onQuit) qButton.setBounds(200, 500, 80, 30) qButton.setToolTipText("Quit Button") panel.add(qButton) newImage = ImageIO.read(io.File("input.png")) resizedImage = newImage.getScaledInstance(500, 500,10) newIcon = ImageIcon(resizedImage) label1 = JLabel("Image and Text",newIcon, JLabel. CENTER) label1.setVerticalTextPosition(JLabel.BOTTOM) label1.setHorizontalTextPosition(JLabel.CENTER) label1.setSize(10,10) panel.add(label1) self.getContentPane().add(panel) self.setTitle("GPU Demo") self.setSize(1200, 600) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True)