def writeMovie(commandArgs, conn): """ Makes the movie. @ returns Returns the file annotation """ log("Movie created by OMERO") log("") message = "" conn.SERVICE_OPTS.setOmeroGroup('-1') session = conn.c.sf gateway = conn scriptService = session.getScriptService() queryService = session.getQueryService() updateService = session.getUpdateService() rawFileStore = session.createRawFileStore() # Get the images images, logMessage = scriptUtil.getObjects(conn, commandArgs) message += logMessage if not images: return None, message omeroImage = images[ 0] # Get the first valid image (should be expanded to process the list) if commandArgs["RenderingDef_ID"] >= 0: omeroImage._prepareRenderingEngine(rdid=commandArgs["RenderingDef_ID"]) pixels = omeroImage.getPrimaryPixels() pixelsId = pixels.getId() sizeX = pixels.getSizeX() sizeY = pixels.getSizeY() sizeZ = pixels.getSizeZ() sizeC = pixels.getSizeC() sizeT = pixels.getSizeT() if (sizeX == None or sizeY == None or sizeZ == None or sizeT == None or sizeC == None): return if (pixels.getPhysicalSizeX() == None): commandArgs["Scalebar"] = 0 cRange = range(0, sizeC) if "Channels" in commandArgs and validChannels(commandArgs["Channels"], sizeC): cRange = commandArgs["Channels"] tzList = calculateRanges(sizeZ, sizeT, commandArgs) timeMap = calculateAquisitionTime(conn, pixelsId, cRange, tzList) if (timeMap == None): commandArgs["Show_Time"] = False if (timeMap != None): if (len(timeMap) == 0): commandArgs["Show_Time"] = False pixelTypeString = pixels.getPixelsType().getValue() frameNo = 1 omeroImage.setActiveChannels(map(lambda x: x + 1, cRange)) renderingEngine = omeroImage._re overlayColour = (255, 255, 255) if "Overlay_Colour" in commandArgs: r, g, b, a = COLOURS[commandArgs["Overlay_Colour"]] overlayColour = (r, g, b) canvasColour = tuple(COLOURS[commandArgs["Canvas_Colour"]][:3]) mw = commandArgs["Min_Width"] if mw < sizeX: mw = sizeX mh = commandArgs["Min_Height"] if mh < sizeY: mh = sizeY ovlpos = None canvas = None if sizeX < mw or sizeY < mh: ovlpos = ((mw - sizeX) / 2, (mh - sizeY) / 2) canvas = Image.new("RGBA", (mw, mh), canvasColour) format = commandArgs["Format"] fileNames = [] # add intro... if "Intro_Slide" in commandArgs and commandArgs["Intro_Slide"].id: intro_duration = commandArgs["Intro_Duration"] intro_fileId = commandArgs["Intro_Slide"].id.val intro_filenames = write_intro_end_slides(conn, commandArgs, intro_fileId, intro_duration, mw, mh) fileNames.extend(intro_filenames) # prepare watermark if "Watermark" in commandArgs and commandArgs["Watermark"].id: watermark = prepareWatermark(conn, commandArgs, mw, mh) # add movie frames... for tz in tzList: t = tz[0] z = tz[1] plane = getPlane(renderingEngine, z, t) planeImage = numpy.array(plane, dtype='uint32') planeImage = planeImage.byteswap() planeImage = planeImage.reshape(sizeX, sizeY) image = Image.frombuffer('RGBA', (sizeX, sizeY), planeImage.data, 'raw', 'ARGB', 0, 1) if ovlpos is not None: image2 = canvas.copy() image2.paste(image, ovlpos, image) image = image2 if "Scalebar" in commandArgs and commandArgs["Scalebar"]: image = addScalebar(commandArgs["Scalebar"], image, pixels, commandArgs) planeInfo = "z:" + str(z) + "t:" + str(t) if "Show_Time" in commandArgs and commandArgs["Show_Time"]: time = timeMap[planeInfo] image = addTimePoints(time, pixels, image, overlayColour) if "Show_Plane_Info" in commandArgs and commandArgs["Show_Plane_Info"]: image = addPlaneInfo(z, t, pixels, image, overlayColour) if "Watermark" in commandArgs and commandArgs["Watermark"].id: image = pasteWatermark(image, watermark) if format == QT: filename = str(frameNo) + '.png' image.save(filename, "PNG") else: filename = str(frameNo) + '.jpg' image.save(filename, "JPEG") fileNames.append(filename) frameNo += 1 # add exit frames... "outro" # add intro... if "Ending_Slide" in commandArgs and commandArgs["Ending_Slide"].id: end_duration = commandArgs["Ending_Duration"] end_fileId = commandArgs["Ending_Slide"].id.val end_filenames = write_intro_end_slides(conn, commandArgs, end_fileId, end_duration, mw, mh) fileNames.extend(end_filenames) filelist = ",".join(fileNames) ext = formatMap[format] movieName = "Movie" if "Movie_Name" in commandArgs: movieName = commandArgs["Movie_Name"] if not movieName.endswith(".%s" % ext): movieName = "%s.%s" % (movieName, ext) movieName = re.sub("[$&\;|\(\)<>' ]", "", movieName) # spaces etc in file name cause problems framesPerSec = 2 if "FPS" in commandArgs: framesPerSec = commandArgs["FPS"] buildAVI(mw, mh, filelist, framesPerSec, movieName, format) figLegend = "\n".join(logLines) mimetype = formatMimetypes[format] if not os.path.exists(movieName): print "mencoder Failed to create movie file: %s" % movieName return None, "Failed to create movie file: %s" % movieName if not commandArgs["Do_Link"]: originalFile = scriptUtil.createFile(updateService, movieName, mimetype, movieName) scriptUtil.uploadFile(rawFileStore, originalFile, movieName) return originalFile, message namespace = omero.constants.namespaces.NSCREATED + "/omero/export_scripts/Make_Movie" fileAnnotation, annMessage = scriptUtil.createLinkFileAnnotation( conn, movieName, omeroImage, output="Movie", ns=namespace, mimetype=mimetype) message += annMessage return fileAnnotation._obj, message
def writeMovie(commandArgs, conn): """ Makes the movie. @ returns Returns the file annotation """ log("Movie created by OMERO") log("") message = "" session = conn.c.sf updateService = session.getUpdateService() rawFileStore = session.createRawFileStore() # Get the images images, logMessage = scriptUtil.getObjects(conn, commandArgs) message += logMessage if not images: return None, message # Get the first valid image (should be expanded to process the list) omeroImage = images[0] if commandArgs["RenderingDef_ID"] >= 0: omeroImage._prepareRenderingEngine(rdid=commandArgs["RenderingDef_ID"]) pixels = omeroImage.getPrimaryPixels() pixelsId = pixels.getId() sizeX = pixels.getSizeX() sizeY = pixels.getSizeY() sizeZ = pixels.getSizeZ() sizeC = pixels.getSizeC() sizeT = pixels.getSizeT() if (sizeX is None or sizeY is None or sizeZ is None or sizeT is None or sizeC is None): return if (pixels.getPhysicalSizeX() is None): commandArgs["Scalebar"] = 0 cRange = range(0, sizeC) cWindows = None cColours = None if "ChannelsExtended" in commandArgs and \ validChannels(commandArgs["ChannelsExtended"], sizeC): cRange = [] cWindows = [] cColours = [] for c in commandArgs["ChannelsExtended"]: m = re.match('^(?P<i>\d+)(\|(?P<ws>\d+)' + '\:(?P<we>\d+))?(\$(?P<c>.+))?$', c) if m is not None: cRange.append(int(m.group('i'))-1) cWindows.append([float(m.group('ws')), float(m.group('we'))]) cColours.append(m.group('c')) elif "Channels" in commandArgs and \ validChannels(commandArgs["Channels"], sizeC): cRange = commandArgs["Channels"] tzList = calculateRanges(sizeZ, sizeT, commandArgs) timeMap = calculateAquisitionTime(conn, pixelsId, cRange, tzList) if (timeMap is None): commandArgs["Show_Time"] = False if (timeMap is not None): if (len(timeMap) == 0): commandArgs["Show_Time"] = False frameNo = 1 omeroImage.setActiveChannels(map(lambda x: x+1, cRange), cWindows, cColours) renderingEngine = omeroImage._re overlayColour = (255, 255, 255) if "Overlay_Colour" in commandArgs: r, g, b, a = COLOURS[commandArgs["Overlay_Colour"]] overlayColour = (r, g, b) canvasColour = tuple(COLOURS[commandArgs["Canvas_Colour"]][:3]) mw = commandArgs["Min_Width"] if mw < sizeX: mw = sizeX mh = commandArgs["Min_Height"] if mh < sizeY: mh = sizeY ovlpos = None canvas = None if sizeX < mw or sizeY < mh: ovlpos = ((mw-sizeX) / 2, (mh-sizeY) / 2) canvas = Image.new("RGBA", (mw, mh), canvasColour) format = commandArgs["Format"] fileNames = [] # add intro... if "Intro_Slide" in commandArgs and commandArgs["Intro_Slide"].id: intro_duration = commandArgs["Intro_Duration"] intro_fileId = commandArgs["Intro_Slide"].id.val intro_filenames = write_intro_end_slides( conn, commandArgs, intro_fileId, intro_duration, mw, mh) fileNames.extend(intro_filenames) # prepare watermark if "Watermark" in commandArgs and commandArgs["Watermark"].id: watermark = prepareWatermark(conn, commandArgs, mw, mh) # add movie frames... for tz in tzList: t = tz[0] z = tz[1] plane = getPlane(renderingEngine, z, t) planeImage = numpy.array(plane, dtype='uint32') planeImage = planeImage.byteswap() planeImage = planeImage.reshape(sizeX, sizeY) image = Image.frombuffer('RGBA', (sizeX, sizeY), planeImage.data, 'raw', 'ARGB', 0, 1) if ovlpos is not None: image2 = canvas.copy() image2.paste(image, ovlpos, image) image = image2 if "Scalebar" in commandArgs and commandArgs["Scalebar"]: image = addScalebar( commandArgs["Scalebar"], image, pixels, commandArgs) planeInfo = "z:"+str(z)+"t:"+str(t) if "Show_Time" in commandArgs and commandArgs["Show_Time"]: time = timeMap[planeInfo] image = addTimePoints(time, pixels, image, overlayColour) if "Show_Plane_Info" in commandArgs and \ commandArgs["Show_Plane_Info"]: image = addPlaneInfo(z, t, pixels, image, overlayColour) if "Watermark" in commandArgs and commandArgs["Watermark"].id: image = pasteWatermark(image, watermark) if format == QT: filename = str(frameNo) + '.png' image.save(filename, "PNG") else: filename = str(frameNo) + '.jpg' image.save(filename, "JPEG") fileNames.append(filename) frameNo += 1 # add exit frames... "outro" # add intro... if "Ending_Slide" in commandArgs and commandArgs["Ending_Slide"].id: end_duration = commandArgs["Ending_Duration"] end_fileId = commandArgs["Ending_Slide"].id.val end_filenames = write_intro_end_slides( conn, commandArgs, end_fileId, end_duration, mw, mh) fileNames.extend(end_filenames) filelist = ",".join(fileNames) ext = formatMap[format] movieName = "Movie" if "Movie_Name" in commandArgs: movieName = commandArgs["Movie_Name"] movieName = os.path.basename(movieName) if not movieName.endswith(".%s" % ext): movieName = "%s.%s" % (movieName, ext) # spaces etc in file name cause problems movieName = re.sub("[$&\;|\(\)<>' ]", "", movieName) framesPerSec = 2 if "FPS" in commandArgs: framesPerSec = commandArgs["FPS"] output = "localfile.%s" % ext buildAVI(mw, mh, filelist, framesPerSec, output, format) mimetype = formatMimetypes[format] if not os.path.exists(output): print "mencoder Failed to create movie file: %s" % output return None, "Failed to create movie file: %s" % output if not commandArgs["Do_Link"]: originalFile = scriptUtil.createFile( updateService, output, mimetype, movieName) scriptUtil.uploadFile(rawFileStore, originalFile, movieName) return originalFile, message namespace = NSCREATED + "/omero/export_scripts/Make_Movie" fileAnnotation, annMessage = scriptUtil.createLinkFileAnnotation( conn, output, omeroImage, ns=namespace, mimetype=mimetype, origFilePathAndName=movieName) message += annMessage return fileAnnotation._obj, message
def saveImageAs(session, parameterMap): # get the services we need queryService = session.getQueryService() updateService = session.getUpdateService() rawFileStore = session.createRawFileStore() rawPixelStore = session.createRawPixelsStore() imageIds = [] if "Image_IDs" in parameterMap: for idCount, imageId in enumerate(parameterMap["Image_IDs"]): iId = long(imageId.getValue()) imageIds.append(iId) else: print "No images" return cIndexes = None theT = 0 if "Channel_Index" in parameterMap: cIndexes = [parameterMap["Channel_Index"]] extension = None format = None if "Extension" in parameterMap: extension = parameterMap["Extension"] if extension in filetypes: format = filetypes[extension] print "Saving all images as .%s files. Format: %s" % (extension, filetypes[extension]) else: print "Invalid extension: %s (not supported by EMAN2). Will attempt to get extensions from image names." % extension extension = None else: print "No extension specified. Will attempt get extensions from image names." originalFiles = [] for imageId in imageIds: image = queryService.get("Image", imageId) n = image.getName().getValue() imageName = os.path.basename(n) # make sure we don't have path as name. if imageName == "": imageName = os.path.basename(n[:-1]) if (extension == None) or (extension not in filetypes): # try to get extension from image name lastDotIndex = imageName.rfind(".") # .rpartition(sep) if lastDotIndex >= 0: extension = imageName[lastDotIndex+1:] if extension in filetypes: format = filetypes[extension] if (extension == None) or (extension not in filetypes): print "File extension from image invalid. Could not export image ID: %d Name: %s Extension: %s" % (imageId, imageName, extension) continue if not imageName.endswith(".%s" % extension): imageName = "%s.%s" % (imageName, extension) print "Preparing to save image: %s" % imageName figLegend = "" # get pixels, with pixelsType query_string = "select p from Pixels p join fetch p.image i join fetch p.pixelsType pt where i.id='%d'" % imageId pixels = queryService.findByQuery(query_string, None) xSize = pixels.getSizeX().getValue() ySize = pixels.getSizeY().getValue() zSize = pixels.getSizeZ().getValue() cSize = pixels.getSizeC().getValue() if pixels.getPhysicalSizeX() == None: physicalSizeX = 1.0 else: physicalSizeX = pixels.getPhysicalSizeX().getValue() if pixels.getPhysicalSizeY() == None: physicalSizeY = 1.0 else: physicalSizeY = pixels.getPhysicalSizeY().getValue() if pixels.getPhysicalSizeZ() == None: physicalSizeZ = 1.0 else: physicalSizeZ = pixels.getPhysicalSizeZ().getValue() if cIndexes == None: cIndexes = range(cSize) # prepare rawPixelStore pixelsId = pixels.getId().getValue() bypassOriginalFile = True rawPixelStore.setPixelsId(pixelsId, bypassOriginalFile) # export an EM image for every channel for theC in cIndexes: e = EMData() em = EMData(xSize,ySize,zSize) # if the physical size was in microns (in OMERO) now it's in Angstroms! em.set_attr('apix_x', physicalSizeX) em.set_attr('apix_y', physicalSizeY) em.set_attr('apix_z', physicalSizeZ) if theC > 0: saveName = imageName.replace(extension, "%s.%s" % (theC, extension)) else: saveName = imageName for z in range(zSize): # get each plane and add to EMData #print "Downloading plane: %d" % z plane2D = scriptUtil.downloadPlane(rawPixelStore, pixels, z, theC, theT) e = EMNumPy.numpy2em(plane2D) em.insert_clip(e,(0,0,z)) em.write_image(saveName) if format == None: format = "" # upload method will pick generic format. print "Uploading image: %s to server with file type: %s" % (saveName, format) # attach to image #fileId = scriptUtil.uploadAndAttachFile(queryService, updateService, rawFileStore, image, imageName, format, figLegend) # want to return the image to client, without attaching it to anything the server # still need to upload it... fileformat = scriptUtil.getFormat(queryService, format) if fileformat == None: # if we didn't find a matching format in the DB, use a generic format. fileformat = scriptUtil.getFormat(queryService, "text/plain") originalFile = scriptUtil.createFile(updateService, saveName, fileformat, saveName) scriptUtil.uploadFile(rawFileStore, originalFile, saveName) print "File uploaded with ID:", originalFile.getId().getValue() originalFiles.append(originalFile) return originalFiles