def createDeepZoomCollection(self, imageNames, imageFolder, collectionFolder): """ Create DeepZoomCollection from jpg or png files. Arguments: imageNames -- list of image file names imageFolder -- path to the images folder collectionFolder -- folder into which the collection will be saved """ #Create paths to image files from the folder imagePaths = [] for image in imageNames: imagePaths.append(os.path.join(imageFolder, image)) #Create paths to DeepZoom image files deepzoomImagePaths = list() for image in imageNames: deepzoomImagePath = os.path.join(collectionFolder, image) deepzoomImagePaths.append( deepzoomImagePath.rstrip(".jpgn") + ".xml") #Create DeepZoom images imageCreator = deepzoom.ImageCreator() for imagePath, deepzoomImagePath in zip(imagePaths, deepzoomImagePaths): imageCreator.create(imagePath, deepzoomImagePath) #create DeepZoom collection os.chdir(collectionFolder) deepzoomImageNames = [] for deepzoomImagePath in deepzoomImagePaths: deepzoomImageNames.append(os.path.split(deepzoomImagePath)[1]) collectionCreator = deepzoom.CollectionCreator() collectionCreator.create(deepzoomImageNames, "collection.xml")
def landing(request): global IMAGE_WIDTH global IMAGE_HEIGHT markers = Marker.objects.filter(new=True) if len(markers) > 0: markers = Marker.objects.all() im = Image.open("media/map.png") IMAGE_WIDTH, IMAGE_HEIGHT = im.size draw = ImageDraw.Draw(im) for pt in markers: pt.check() x, y = normalize(pt.getX(), pt.getY()) draw.ellipse([(x - SQSIZE, y - SQSIZE), (x + SQSIZE, y + SQSIZE)], fill=pt.color()) im.save("media/map_full.png", "PNG") dz_creator = deepzoom.ImageCreator(tile_size=128, tile_overlap=2, tile_format="png", image_quality=0.8, resize_filter="bicubic") dz_creator.create("media/map_full.png", "media/map_full.dzi") return render_to_response("landing.html", locals(), RequestContext(request))
def convert_to_dzi(src, dest='./', level=None, max_pixels=50000000, tile_size=254, tile_overlap=1, tile_format='jpg', image_quality=0.75, resize_filter='bicubic', verbose=False): """ Convert the image src to a dzi file and save in dest. Inputs: src - Source to the image to be converted to dzi format. dest - Location to save the new dzi file. (default: './') level - The Openslide level at which to save the dzi file. If set to none, it is set to the value which maximizes the number of pixels subject to the max_pixels size. (default: None) max_pixels - The maximum number of pixels allowed if level is not specified. if level is specified, has no effect. (default: 50000000) Outputs: name_dzi - The full path of the new dzi file created. """ if level is None: level = get_level_with_max_pixels(src, max_pixels) if level is -1: level = 0 orig_dims = open_slide(src).dimensions k = orig_dims[0] / orig_dims[1] c = sqrt(max_pixels / k) opt_dims = (int(k * c), int(c)) else: slide_dims = open_slide(src).level_dimensions opt_dims = slide_dims[level] else: slide_dims = open_slide(src).level_dimensions opt_dims = slide_dims[level] if verbose: print("Image Level: " + str(level)) print("Dimensions: " + str(opt_dims)) slide = open_slide(src).read_region((0, 0), level, opt_dims) # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator(tile_size=tile_size, tile_overlap=tile_overlap, tile_format=tile_format, image_quality=image_quality, resize_filter=resize_filter) # Create Deep Zoom image pyramid from source name, _ = splitext(basename(src)) name_dzi = join(dest, name + '.dzi') creator.create(slide, name_dzi) return name_dzi
def generateImageTiles(imageName, imageId): # Creating Deep Zoom Image creator with default parameters creator = deepzoom.ImageCreator(tile_size=128, tile_overlap=2, tile_format="png", image_quality=0.8, resize_filter="bicubic") status = {}; dzi_base = IMAGE_RESOURCE_BASE + '/dzifiles/' img_base = IMAGE_RESOURCE_BASE + '/sources/' img_location = img_base + imageName dzi_location = dzi_base + imageId + '.dzi' logger.debug("Creating deepzoom files for "+ imageId + " (located at " + img_location + ") in "+dzi_location) # Create Deep Zoom image pyramid from source if os.path.isfile(dzi_location) == False: try: creator.create(img_location, dzi_location) logger.debug("Successfully created deepzoom files for "+ imageId + "(located at " + img_location + ") in " + dzi_location) status['message'] = 'OK' except IOError: logger.debug("Error creating DZI file - I/O Error") status['NOK'] = 'Error reaching image resource server' else: logger.debug("Deepzoom file already exists on Image Server") return simplejson.dumps(status)
def main (arg1, arg2): # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator(tile_size=128, tile_overlap=2, tile_format="png", image_quality=0.8, resize_filter="bicubic") # Create Deep Zoom image pyramid from source creator.create(arg1, arg2)
def img2dzi(infile, outdir): # Create Deep Zoom Image pyramid creator = deepzoom.ImageCreator(tile_size=254, tile_overlap=1, tile_format="jpg", image_quality=0.75, resize_filter="bicubic") creator.create(infile, outdir) return [creator.descriptor.width, creator.descriptor.height]
def create_deepzoom_stack(input_image, output_dzi): import deepzoom dz_params = { 'tile_size': 256, 'tile_overlap': 1, 'tile_format': "png", 'resize_filter': "antialias" } # cubic bilinear bicubic nearest antialias creator = deepzoom.ImageCreator(tile_size=dz_params['tile_size'], tile_overlap=dz_params['tile_overlap'], tile_format=dz_params['tile_format'], resize_filter=dz_params['resize_filter']) creator.create(input_image, output_dzi)
def write_node_data(self, node, path, data): super(DziFileCacher, self).write_node_data(node, path, data) filepath = os.path.join(path, node.get_file_name()) if not filepath.endswith(".png"): return with self.get_read_handle(filepath) as fh: if not os.path.exists(path): os.makedirs(path) creator = deepzoom.ImageCreator(tile_size=512, tile_overlap=2, tile_format="png", image_quality=1, resize_filter="nearest") creator.create(fh, "%s.dzi" % os.path.splitext(filepath)[0])
def createImg(filePath): SOURCE = filePath # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator( tile_size=128, tile_overlap=2, tile_format="png", image_quality=0.8, resize_filter="bicubic", ) filepath, tmpfilename = os.path.split(filePath) newname = uuid.uuid4().hex dzi_path = filepath + "/diz/" + newname + ".dzi" # Create Deep Zoom image pyramid from source creator.create(SOURCE, dzi_path) return dzi_path
def snapshot(self): camera = PiCamera() camera.vflip = self.VFLIP camera.hflip = self.HFLIP camera.resolution = (self.HRES / 2, self.VRES / 2) log.debug("Take a snapshot") camera.annotate_text_size = 120 camera.annotate_background = picamera.Color('black') camera.annotate_text = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') camera.capture(self.path + "snapshot.png") camera.close() shutil.rmtree(self.path + "snapshot_files", ignore_errors=True) self.log.debug("Make the snapshot zoomable") deepzoom.ImageCreator().create(self.path + "snapshot.png", self.path + "snapshot.dzi")
def createdz(fullimgname, fullwritename=None): if fullwritename == None: fullwritename = fullimgname fullwritename = fullwritename[:-3] + 'dzi' print "--------> create dz at ", fullwritename # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator(tile_size=512, tile_overlap=2, tile_format="jpg", image_quality=1, resize_filter="bicubic") # Create Deep Zoom image pyramid from source print("Now creating dzi from source:" + fullimgname) creator.create(fullimgname, fullwritename) print "-------> saved dzi at ", fullwritename print("Now return dzi to source:" + fullwritename) return fullwritename
def make_pyramid(image_in, pyramid_archive_path, descriptor_name): temp_mount = tempfile.mkdtemp(dir='/tmp') with ArchiveMount(pyramid_archive_path, temp_mount) as pyramid_contain_dir: pyramid_descriptor = pth.join(pyramid_contain_dir, descriptor_name) creator = deepzoom.ImageCreator(tile_size=128, tile_overlap=2, tile_format="jpg", image_quality=0.95, resize_filter="bicubic") load_img = (image_in if isinstance(image_in, np.ndarray) else file_to_cv2(image_in)) creator.create(load_img, pyramid_descriptor) debug_log("Pyramid archive", pyramid_archive_path, "created.") #os.rmdir(temp_mount) shutil.rmtree(temp_mount) return True
def repaint(): global IMAGE_WIDTH global IMAGE_HEIGHT markers = Marker.objects.all() if len(markers) > 0: im = Image.open("media/map.png") IMAGE_WIDTH, IMAGE_HEIGHT = im.size draw = ImageDraw.Draw(im) for pt in markers: pt.check() x, y = normalize(pt.getX(), pt.getY()) draw.ellipse([(x - SQSIZE, y - SQSIZE), (x + SQSIZE, y + SQSIZE)], fill=pt.color()) im.save("media/map_full.png", "PNG") dz_creator = deepzoom.ImageCreator(tile_size=128, tile_overlap=2, tile_format="png", image_quality=0.8, resize_filter="bicubic") dz_creator.create("media/map_full.png", "media/map_full.dzi")
import re MAX_PAGES = 10 PAGE_COUNT = {} def ensure_dir(filename): directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator(tile_size=512, tile_overlap=2, image_quality=1, tile_format="tif", resize_filter="antialias") tiff_list = open( 'tiffs.txt', 'r' )\ .read()\ .split( '\n' ) for tiff_url in tiff_list: print tiff_url parts = re.match( r'http://lcweb2\.loc\.gov/master/pnp/([a-z0-9]*)/([a-z0-9]*)/([a-z0-9]*)/([a-z0-9]*)u\.tif', tiff_url).groups() agg = parts[1] id = parts[2]
print("==== Writing output to: ====") print(OUTPUT_DIR) print("overwrite: {}".format(overwrite)) print("dir exists: {}".format(os.path.exists(OUTPUT_DIR))) print("============================") if os.path.exists(OUTPUT_DIR): if not overwrite: raise Exception("Set overwrite to True to overwrite existing directory!") else: shutil.rmtree(OUTPUT_DIR) os.makedirs(OUTPUT_DIR) ### Create DeepZoom Tiles. ### PIL.Image.MAX_IMAGE_PIXELS = 13151043584 creator = deepzoom.ImageCreator(tile_size=256, tile_overlap=1, tile_format="jpg", image_quality=0.8, resize_filter="bilinear") TSNE_FILES_NAME = "tsne_{}x{}_{}px".format(hum_resolution, hum_resolution, patch_px) creator.create(INPUT_TSNE_IMAGE, os.path.join(OUTPUT_DIR, TSNE_FILES_NAME+".dzi")) ### Create Embedding HTML. ### embedding_html_template = open("embedding_template.html", "r") lines = [] template_repl = {"<<TSNE_FILES_PATH>>": TSNE_FILES_NAME+"_files/", "<<HEIGHT>>": resolution, "<<WIDTH>>": resolution, } template_repl = {k:str(v) for k,v in template_repl.items()} for line in embedding_html_template:
# # add jsonrpc2 support... # import deepzoom # Specify your source image SOURCE = "/my/rawdata/bigbrain/pm3500o.png" # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator(tile_size=254, tile_overlap=1, tile_format="jp2", image_quality=0.8, resize_filter="bicubic") # Create Deep Zoom image pyramid from source creator.create(SOURCE, "/my/rawdata/bigbrain/pm3500o.dzi")
#!/usr/bin/env python # -*- coding: utf-8 -*- import deepzoom import os os.listdir('.') for element in os.listdir('.'): if element.endswith('.JPG') or element.endswith('.jpg'): name, ext = element.split(".") # Specify your source image SOURCE = element DESTINATION = name + ".dzi" # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator(tile_size=128, tile_overlap=2, tile_format="png", image_quality=0.8, resize_filter="bicubic") # Create Deep Zoom image pyramid from source creator.create(SOURCE, DESTINATION) # print("succes" ) #else: # print("fail" )
import deepzoom import glob import os.path import shutil if not os.path.exists("images/suitcases"): os.mkdir("images/suitcases") images = glob.glob("assets/suitcases/*-content.png") creator = deepzoom.ImageCreator(tile_format="png") for image in images: output = "images/suitcases/" + os.path.splitext(os.path.basename(image))[0] + "/image.dzi" creator.create(image, output) #shutil.copytree("assets/buttons/", "images/buttons") print "Done."
def worker(wsi_name, web_dir, shrink_factor): # disable safety checks for large images PIL.Image.MAX_IMAGE_PIXELS = None assert (wsi_name[-4:] == ".npy") wsi_prefix = wsi_name[:-4] prefix_path = os.path.join(web_dir, "images", wsi_prefix) npy_path = prefix_path + ".npy" png_path = prefix_path + ".png" dzi_path = prefix_path + ".dzi" base_html_path = "npy2dzi.html" new_html_path = os.path.join(web_dir, "index.html") openseadragon_src = "openseadragon/" openseadragon_dst = os.path.join(web_dir, "openseadragon/") iter_name = web_dir[web_dir.rindex("/") + 1:] title = iter_name + " " + wsi_name START_TIME = time.time() print("Loading .npy file") img = np.load(npy_path) print("Execution time (s):", time.time() - START_TIME) print("Done.\n") START_TIME = time.time() print("Reducing .npy file") if shrink_factor == 1: comp_img = img else: comp_img = np.zeros((img.shape[0] // shrink_factor, img.shape[1] // shrink_factor, img.shape[2]), dtype=np.uint32) print(comp_img.shape) for i in range(shrink_factor): j1 = img.shape[0] - img.shape[0] % shrink_factor j2 = img.shape[1] - img.shape[1] % shrink_factor comp_img += img[i:j1:shrink_factor, i:j2:shrink_factor] comp_img //= shrink_factor print("Execution time (s):", time.time() - START_TIME) print("Done.\n") # create png files START_TIME = time.time() print("Creating .png file") Image.fromarray(comp_img.astype(np.uint8)).save(png_path, compress_level=1) print("Execution time (s):", time.time() - START_TIME) print("Done.\n") # create dzi files START_TIME = time.time() print("Creating .dzi file") creator = deepzoom.ImageCreator( tile_size=256, tile_overlap=0, tile_format="png", image_quality=1.0, ) creator.create(png_path, dzi_path) print("Execution time (s):", time.time() - START_TIME) print("Done.\n") START_TIME = time.time() print("Creating HTML files") # create html files with open(base_html_path, "r") as f: HTML_STR = "".join(f.readlines()) HTML_STR = HTML_STR.replace("{REPLACE_wsi_prefix}", os.path.join("images", wsi_prefix)) HTML_STR = HTML_STR.replace("{REPLACE_title}", title) with open(new_html_path, "w") as f: f.write(HTML_STR) # copy openseadragon if not os.path.isdir(openseadragon_dst): shutil.copytree(openseadragon_src, openseadragon_dst) print("Execution time (s):", time.time() - START_TIME) print("Done.\n")
#!/usr/bin/env python # -*- coding: utf-8 -*- import deepzoom # Create Deep Zoom Image creator with weird parameters creator = deepzoom.ImageCreator() # Create Deep Zoom image pyramid from source for index in range(1, 7): source = "images/%d.jpg" % index destination = "images/%d.dzi" % index print(source, destination) creator.create(source, destination)
def generate_tiles(filename, image_id, log_dictionary, page_number, uploaded_file_id, process_start_time): """ This function generates tiles for the high resolution image that is created. The tile details are stored in the 'tiles' table. Input: High resolution PNG Output: Tiles for the input PNG """ import tempfile, shutil import deepzoom import mysql.connector from database import login_info import config import os import time tmpdir = tempfile.mkdtemp() tmpimg = str(image_id) + "_image.png" tmpdzi = str(image_id) + "_tmp.dzi" image_name = tmpdir + "/" + tmpimg dzi_name = tmpdir + "/" + tmpdzi with open(image_name, "wb") as img_file: with open(filename, "rb") as read_file: img_file.write(read_file.read()) creator = deepzoom.ImageCreator(tile_size=config.tile_pixel_size, tile_overlap=2, tile_format="png", image_quality=1, resize_filter="bicubic") creator.create(image_name, dzi_name) width, height = creator.image.size basepath = tmpdir + "/" + str(image_id) + "_tmp_files" db = mysql.connector.Connect(**login_info) cursor = db.cursor() for d in os.listdir(basepath): curpath = os.path.join(basepath, d) if os.path.isdir(curpath): for f in os.listdir(curpath): if os.path.isfile(os.path.join(curpath, f)): with open(os.path.join(curpath, f), "rb") as tile_file: tile_blob = tile_file.read() cursor.execute( "INSERT INTO tiles values (NULL,%s,%s,%s)", ( str(image_id), d + '_' + f[:-4], tile_blob, )) db.commit() shutil.rmtree(tmpdir) cursor.close() db.close() process_end_time = time.time() total_time = str( round(process_end_time - process_start_time, config.time_digit_precision)) log_dictionary['all_steps'] += "[" + str( page_number ) + "] Tile Generation Complete. Details Added to 'tiles' table. Time " + total_time + "\n" print("[" + str(uploaded_file_id) + "," + str(page_number) + "] Generated Tiles and Added Details to 'tiles' table. Time: " + total_time) config.write_to_file( config.log_file_name, "[" + str(uploaded_file_id) + "," + str(page_number) + "] Generated Tiles and Added Details to 'tiles' table. Time: " + total_time) return log_dictionary
#!/usr/bin/env python import os, sys, subprocess import deepzoom if __name__ == "__main__": source = sys.argv[1] dest = sys.argv[2] creator = deepzoom.ImageCreator(tile_size=512, tile_overlap=2, tile_format="jpg", image_quality=0.9, resize_filter="bicubic") creator.create(source, dest)
def upload(request): #由于上传文件很大,处理时间长,需要配置nginx最大上传和响应时间 file = request.FILES.get('file', None) if not file: return JsonResponse({'status': False, 'msg': 'ok'}) name = request.FILES['file'].name device_num = request.POST.get('device_num', '1') co_num = request.POST.get('co_num', '1') file_path = os.path.join(settings.STATIC_ROOT, 'upload', name) #if not os.path.exists(file_path): # 文件夹不存在则创建 # os.mkdir(file_path) process_get = Process.objects.all().order_by('id').last() process_get.status = 1 process_get.save() process_all_num = len(list(file.chunks())) j = 0 with open(file_path, 'wb') as fp: # 写文件 for i in file.chunks(): fp.write(i) j += 1 #num_progress = j/process process_get = Process.objects.all().order_by('id').last() process_get.process = int((j * 100 / process_all_num) / 2) process_get.save() #处理为deepzoom photo_path = os.path.join(settings.STATIC_ROOT, 'upload', 'photo') isExists = os.path.exists(photo_path) if not isExists: os.makedirs(photo_path) unzip_file(file_path, photo_path) os.remove(file_path) photo_list = os.listdir(photo_path) photo_list.sort(key=lambda x: int(os.path.splitext(x)[0])) process_all_num = len(photo_list) j = 0 creator = deepzoom.ImageCreator( tile_size=256, tile_overlap=1, tile_format="jpg", image_quality=1, #resize_filter="bicubic", #resize_filter="nearest", ) for photo in photo_list: photo_src = os.path.join(photo_path, photo) transpose_img(photo_src) root_path = os.path.join(STATIC_ROOT, "D{}/co{}".format(device_num, co_num)) xml_path = os.path.join(root_path, 'xml') isExists = os.path.exists(xml_path) if not isExists: os.makedirs(xml_path) photo_num = os.path.splitext(photo)[0] photo_dest = os.path.join(root_path, photo_num) xml_dest = os.path.join(xml_path, '{}.xml'.format(photo_num)) creator.create(photo_src, photo_dest, xml_dest) os.remove(photo_src) j += 1 #num_progress = j/process process_get = Process.objects.all().order_by('id').last() process_get.process = 50 + int((j * 100 / process_all_num) / 2) process_get.save() return JsonResponse({'status': True, 'msg': 'ok'})