Best Python code snippet using fMBT_python
tileImage.py
Source:tileImage.py  
1#!/usr/bin/python2# -*- coding: utf-8 -*-3###############################################################################4#                                                                             #5#    BrainSlices Software                                                     #6#                                                                             #7#    Copyright (C) 2012-2013 Jakub M. Kowalski                                #8#                                                                             #9#    This software is free software: you can redistribute it and/or modify    #10#    it under the terms of the GNU General Public License as published by     #11#    the Free Software Foundation, either version 3 of the License, or        #12#    (at your option) any later version.                                      #13#                                                                             #14#    This software is distributed in the hope that it will be useful,         #15#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #16#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #17#    GNU General Public License for more details.                             #18#                                                                             #19#    You should have received a copy of the GNU General Public License        #20#    along with this software.  If not, see http://www.gnu.org/licenses/.     #21#                                                                             #22###############################################################################23import os24import sys25import math26import json27import subprocess28import tempfile29from optparse import OptionParser30def ensureDirPath(directory):31  if not os.path.exists(directory):32    os.makedirs(directory)33def ensureDir(directory):34  if not os.path.exists(directory):35    os.mkdir(directory)36directoryName = os.path.abspath(os.path.dirname(__file__))37class CorruptedImageError(Exception):38  pass39class imageTiler(object):40  def __init__(self, filename, imageRes, threads = 1, limit = 512*1024*1024):41    self.filename = filename42    self.imageRes = imageRes43    self.invalid = None44    if (threads <= 0):45      raise ValueError("Number of threads must be positive.")46    if (limit < 0):47      raise ValueError("Memory limit must be non negative number.")48    self.threads = threads49    self.limit = limit50    self.tmpfile = tempfile.NamedTemporaryFile(dir='/tmp',51                                               prefix='SkwarkiTiledImage_',52                                               suffix='.raw')53  def tileStack(self, destDir, tileWidth, tileHeight, imageLeft = 0., imageTop = 0., jpgQuality = None):54    # identify an image...55    try:56      self.identify()57    except:58      print "ERROR:"59      print self.invalid60      raise61    # ...and rip the RGB data62    # suggested ImageMagick 6.6.9-763    stream =  ['stream']64    stream += ['-map', 'rgb']65    stream += ['-storage-type', 'char']66    stream += ['-regard-warnings']67    stream += [self.filename, self.tmpfile.name]68    print ' '.join(stream)69    processStream = subprocess.Popen(stream, stderr = subprocess.PIPE)70    pStdOut, pStdErr = processStream.communicate()71    if processStream.returncode != 0:72      self.invalid = pStdErr73      print pStdErr74    maxZoomLevel = int(math.ceil(math.log(max(float(self.imageWidth) / tileWidth,75                                              float(self.imageHeight) / tileHeight), 2)))76    ensureDirPath(destDir)77  78    fh = open(os.path.join(destDir, 'info.json'), 'w')79    json.dump({'status': True,80               'logged': False,81               'message': None,82               'data': {'imageWidth': self.imageWidth,83                        'imageHeight': self.imageHeight,84                        'pixelSize': self.imageRes,85                        'imageLeft': imageLeft,86                        'imageTop': imageTop,87                        'tileWidth': tileWidth,88                        'tileHeight': tileHeight}}, fh)89    fh.close()90  91    for zoomLevel in xrange(maxZoomLevel + 1):92      print zoomLevel93      zoomLevelPath = os.path.join(destDir, "tiles", "%d" % zoomLevel)94      scaleFactor = 0.5 ** (maxZoomLevel - zoomLevel)95      self.tile(zoomLevelPath,96                tileWidth,97                tileHeight,98                scaleFactor,99                quality = jpgQuality)100    # create image containing the original bitmap101    raw2png = [os.path.join(directoryName, 'imageProcessing', 'raw2png')]102    raw2png += ['-size', str(self.imageWidth), str(self.imageHeight)]103    raw2png += ['-compression', '9', '-rle']104    raw2png += ['-limit', str(self.limit / 4)] # just for safety105    raw2png += ['-src', self.tmpfile.name]106    raw2png += ['-dst', os.path.join(destDir, 'image.png')]107    process2png = subprocess.Popen(raw2png)108    process2png.wait()109  def identify(self):110    identify = ['identify', '-regard-warnings']111    identify += ['-format', '%w %h']112    identify += [self.filename]113    processIdentify = subprocess.Popen(identify,114                                       stdout = subprocess.PIPE,115                                       stderr = subprocess.PIPE)116    pStdOut, pStdErr = processIdentify.communicate()117#   if processIdentify.returncode != 0:118#     raise CorruptedImageError, pStdErr  119    try:120      self.imageWidth, self.imageHeight = map(int, pStdOut.split())121    except ValueError:122      self.invalid = pStdErr123      if processIdentify.returncode != 0:124        raise CorruptedImageError, pStdErr125      else:126        raise127    except:128      self.invalid = pStdErr129      raise130  131  def tile(self, destDir, tileWidth, tileHeight, scaleFactor = 1, quality = None):132    ensureDirPath(destDir)133    levelWidth = int(round(scaleFactor * self.imageWidth))134    levelHeight = int(round(scaleFactor * self.imageHeight))135    xTiles = int(math.ceil(levelWidth / float(tileWidth)))136    yTiles = int(math.ceil(levelHeight / float(tileHeight)))137    for x in xrange(xTiles):138      columnPath = os.path.join(destDir, '%d' % x)139      ensureDir(columnPath)140    tile =  [os.path.join(directoryName, 'imageProcessing', 'tileStreamedImageJPG')]141    tile += ['-size', str(self.imageWidth), str(self.imageHeight)]142    tile += ['-scale', str(levelWidth), str(levelHeight)]143    tile += ['-lanczos' if scaleFactor != 1 else '-box']144    tile += ['-limit', str(self.limit)]145    tile += ['-threads', str(self.threads)]146    tile += ['-tile', str(tileWidth), str(tileHeight)]147    tile += ['-pattern', os.path.join(destDir, '%X/%Y.jpg')]148    tile += ['-src', self.tmpfile.name]149    if quality != None:150      tile += ['-quality', str(quality)]151    print ' '.join(tile)152    processTile = subprocess.Popen(tile)153    processTile.wait()154def tileImage(filename, tileWidth, tileHeight, imageRes, destDir, imageLeft = 0., imageTop = 0., jpgQuality = None):155  tiler = imageTiler(filename, imageRes)156  tiler.tileStack(destDir, tileWidth, tileHeight, imageLeft, imageTop, jpgQuality)157  return tiler.invalid158if __name__ == '__main__':159  usage = "Usage: %prog [options] <filename> <destination>"160  parser = OptionParser(usage=usage)161  parser.add_option('-x', '--width', action='store', type='int', dest='width',162                    default=256, help='tile width')163  parser.add_option('-y', '--height', action='store', type='int', dest='height',164                    default=256, help='tile height')165  parser.add_option('-X', '--left', action='store', type='float', dest='left',166                    default=0., help='left offset [um]')167  parser.add_option('-Y', '--top', action='store', type='float', dest='top',168                    default=0., help='top offset [um]')169  parser.add_option('-p', '--pixel', action='store', type='float',170                    dest='pixel', default=None, help='pixel size [um]')171  parser.add_option('-r', '--res', '--dpi', action='store', type='float',172                    dest='dpi', default=72.,help='image resolution [DPI]')173  parser.add_option('-q', '--quality', action='store', type='int',174                    dest='quality', default=None, help='JPG quality')175  parser.add_option('-t', '--threads', action='store', type='int',176                    dest='threads', default=1, help='Number of threads')177  parser.add_option('-l', '--limit', action='store', type='int',178                    dest='limit', default=512*1024*1024, help='Memory limit')179  options, args = parser.parse_args()180  if len(args) != 2:181    parser.print_help()182    exit()183  if options.threads <= 0:184    sys.stderr.write("Error: number of threads must be positive.\n")185    exit()186  if options.limit < 0:187    sys.stderr.write("Error: memory limit mustn't be negative.\n")188    exit()189  if options.quality != None and (options.quality < 0 or options.quality > 100):190    sys.stderr.write("Error: quality must be within range [0, 100].\n")191    exit()192  if options.height <= 0:193    sys.stderr.write("Error: tile height must be positive.\n")194    exit()195  if options.width <= 0:196    sys.stderr.write("Error: tile width must be positive.\n")197    exit()198  if options.dpi <= 0:199    sys.stderr.write("Error: image resolution must be positive.\n")200    exit()201  if options.pixel != None and options.pixel <= 0:202    sys.stderr.write("Error: pixel size must be positive.\n")203    exit()204  filename = args[0]205  imageRes = options.pixel if options.pixel != None else 25400. / options.dpi206  destDir = args[1]207  sys.exit(tileImage(filename, options.width, options.height, imageRes,...DSLR.py
Source:DSLR.py  
...82       Shutter time in second83   '''84   subprocess.check_call(['gphoto2', '-B', str(shutter), '--capture-image-and-download', '--filename', filename])85   86def raw2png(raw, png):87    '''88    Convert raw image to png image89    Parameters90    ----------91    raw : string92        Raw filename93    png : string94        Output filename95    '''96    command = 'dcraw -4 -w -c ' + raw + ' | convert - ' + png97    proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)98    return proc.communicate()99    100def raw2png_resize(raw, png):101    '''102    Convert raw image to png image103    Parameters104    ----------105    raw : string106        Raw filename107    png : string108        Output filename109    '''110    command = 'dcraw -4 -w -c ' + raw + ' | convert - -resize 25% ' + png111    proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)112    proc.communicate()113    subprocess.check_call(['rm', '-f', raw])114    115def raw2png_crop(raw, png, roi):116    '''117    Convert raw image to png image with cropping118    Parameters119    ----------120    raw : string121        Raw filename122    png : string123        Output filename124    roi : string125        Crop region, imagemagick format.126    '''127    command = 'dcraw -4 -w -c ' + raw + ' | convert - -crop ' + roi + ' +repage ' + png128    proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)129    proc.communicate()130    subprocess.check_call(['rm', '-f', raw])131    132def capture_and_show_intensity(roi):133    '''134    Capture and print mean intensity of the region135    Parameters136    ----------137    roi : string138        Crop region, imagemagick format.139    '''140    set_iso400()141    subprocess.check_call(['rm', '-rf', 'temp.nef'])142    capture_and_save('temp.nef')143    raw2png_crop('temp.nef', 'temp.ppm', roi)144    img = cv2.imread('temp.ppm', -1)145    print np.mean(img)146    147camera_conf_names = {148        'shutter': '/main/capturesettings/shutterspeed',149        'ISO': '/main/imgsettings/iso',150        'f-number': '/main/capturesettings/f-number'}151        152#def capture_multiple_gains():153#    base_shutter = 41 # 3154#    base_ISO = 0 # 100155#    base_f_number = 5 # f/10156#    set_property(camera_conf_names['f-number'], base_f_number)157#    for iso in range(0, 24, 3):158#        set_property(camera_conf_names['shutter'], base_shutter)159#        set_property(camera_conf_names['ISO'], base_ISO)160#        base_shutter -= 3161#        base_ISO += 3162#        capture_and_save('ISO'+str(iso)+'.nef')163#        raw2png('ISO'+str(iso)+'.nef', 'ISO'+str(iso)+'.png')164#        165#def print_values():166#    print 'target brightness: 16384'    167#    for iso in range(0, 24, 3):168#        print iso, np.amax(cv2.imread('ISO'+str(iso)+'.png', -1))169        170def set_ISO(value=6):171    '''172    Set ISO value.173    Parameters174    ----------175    value : int176        Index of configurable property values.177        ...raw2png.py
Source:raw2png.py  
1#!/usr/bin/python2#3#  (c) 2015 Mike Chaberski4#  5#  MIT License6from __future__ import with_statement7import os.path8from PIL import Image9import argparse10import csv11import sys12from math import sqrt13MAX_INPUT_LENGTH = 16 * 1024 * 1024   # 16 MB in bytes14def guess_dims(rawfile_pathname, input_width=None, warnaboutguess=False):15    if input_width is None and not warnaboutguess:16        print("raw2png: guessing image width by assuming square: ", rawfile_pathname, file=sys.stderr)17    rawfile_length = os.path.getsize(rawfile_pathname)18    assert rawfile_length < MAX_INPUT_LENGTH, \19                ('input exceeds max length: ' + 20                str(rawfile_length) +' > ' + str(MAX_INPUT_LENGTH))21    if input_width is None:22        input_width = int(sqrt(rawfile_length))23    image_height = rawfile_length / input_width24    if input_width * image_height != rawfile_length:25        print(("raw2png: bad guess: product width*height != file length; " +26                        "%d * %d = %d != %d" % (input_width, image_height,27                        input_width * image_height, rawfile_length)), file=sys.stderr)28    return input_width, image_height29def create_widths_map(args):30    m = dict()31    with open(args.widths_from, 'r') as ifile:32        reader = csv.reader(ifile, delimiter=' ')33        for row in reader:34            #print >> sys.stderr, row35            if args.wholenames: imname = row[0]36            else: imname = os.path.basename(row[0])37            w = int(row[1])38            m[imname] = w39    return m40def convert(raw_pathname, png_pathname, width, height, args):41    with open(raw_pathname, 'rb') as rawfile:42        data = rawfile.read()43    im = Image.fromstring(mode='L', size=(width, height), data=data)44    im.save(png_pathname, 'PNG')45    if args.verbose:46        print("%s -> %s (%d x %d)" % (raw_pathname, png_pathname, width, height), file=sys.stderr)47def main(args):48    if len(args.rawfile) > 1 and args.output is not None:49        print("raw2png: can't specify output for multiple files", file=sys.stderr)50        return 151    widthmap = None52    specwidth = args.width53    if args.widths_from is not None:54        widthmap = create_widths_map(args)55    for rawfile in args.rawfile:56        imname = rawfile57        if not args.wholenames: imname = os.path.basename(rawfile)58        if widthmap is not None:59            if imname in widthmap: specwidth = widthmap[imname]60            elif args.width is not None: specwidth = args.width61        image_width, image_height = guess_dims(rawfile, specwidth, True)62        outname = args.output63        if outname is None:64            outname = os.path.splitext(rawfile)[0] + ".png"65        convert(rawfile, outname, image_width, image_height, args)66    return 067def main():68    parser = argparse.ArgumentParser()69    parser.add_argument("rawfile", nargs='+', default=list(), 70            help="raw grayscale image file to convert to PNG format")71    parser.add_argument("-v", "--verbose", action="store_true", default=False)72    parser.add_argument("-o", "--output", metavar="PATHNAME", dest="output")73    parser.add_argument("--wholenames", action="store_true", default=False, 74            help="use whole pathnames when creating map from --widths-from" 75            + " file (default is to use basenames only)")76    parser.add_argument("-w", "--width", metavar="WIDTH", type=int, 77            help="image width (if not square)")78    parser.add_argument("--widths-from", metavar="WIDTHSFILE", 79            help="specify file to get raw image widths from; file should "80            + "contain image filenames and widths, separated by a space")81    args = parser.parse_args()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
