Exemple #1
0
 def resize_image(self, field, size, source, add_watermark=False):
     original = Image.open(source.path)
     fmt = original.format
     img = original.copy()
     img.thumbnail(size, Image.ANTIALIAS)
     if add_watermark:
         img = watermark(img, settings.MEDIA_ROOT + 'resources/small_watermark.png')
         img = watermark(img, settings.MEDIA_ROOT + 'resources/large_watermark.png',position='center',opacity=0.1)
     updateContent(field, source.name, img, fmt)
Exemple #2
0
def watermark_response(image, type='tile', wm=None, size=None):
    u"""Render image with watermark to HttpResponse and return it
    
    If `size` is specified, rendered image will be thumbnail to the size.
    If `watermark` is specified, that is used insted of PIL.Image created 
    by `settings.STORAGE_WATERMARK_PATH`.
    
    Attribute:
        image        - PIL.Image instance
        type         - Watermark rendering type
        wm           - PIL.Image instance for watermark (Default: None)
        size         - thumbnail size represented by list like (w, h) (Default: None)
    
    Return:
        response     - HttpResponse instance
    """
    if size:
        image.thumbnail(size, Image.ANTIALIAS)
    
    if not wm:
        WATERMARK = settings.STORAGE_WATERMARK_PATH
        wm = Image.open(WATERMARK)
    elif not isinstance(wm, Image):
        raise AttributeError('`watermark` attribute must be PIL.Image instance')
    image = watermark.watermark(image, wm, 'tile', 0.3)
    response = HttpResponse(mimetype='image/png')
    image.save(response, 'PNG')
    return response
Exemple #3
0
def get_photos(api, images, watermark_file=''):
    """
    Возвращает массив, содержащий файлы изображений.

    Параметры:
    -- api - объект класса API для доступа к ВКонтакте API
    -- images - массив идентификаторов фотографий или ссылок на изображения (['photoXXX_XX', 'http://XXX', ...])
    """
    
    photos_ids = [image.replace('photo', '') for image in images if image.find('photo') >= 0]
    image_urls = [image for image in images if re.search(r'https?://', image) is not None]


    # Получить URL фотографий
    if len(photos_ids) > 0:
        response = api.photos.getById(photos=','.join(photos_ids))
        image_urls.extend(
            [photo['src_big'] for photo in response]
        )

    # Сохранить в памяти
    content = []
    for url in image_urls:
        try:
            content.append( urllib2.urlopen(url).read() )
        except:
            continue

    # Если надо проставить водяные знаки
    if watermark_file != '':
        mark = Image.open(watermark_file)
        
        # Пройтись по всем фотографиям
        for index in xrange(len(content)):
            # Обработать в памяти
            im = Image.open(StringIO(content[index]))
            buf = StringIO()
            watermark(im, mark, (im.size[0]-mark.size[0], im.size[1]-mark.size[1]), 0.5).save(buf, 'jpeg')
                
            # Сохранить обработанную фотку в массиве фотографий
            buf.seek(0)
            content[index] = buf.read()
    
    # Вернуть ответ
    return content
Exemple #4
0
def image_it(path_to_original, rotation):
	im = Image.open(path_to_original)
	mark = Image.open('/home/rob/grifter/newcard-trans2.png')
	#size = 500,375,180
	size = 800,500,180
	im.thumbnail(size, Image.ANTIALIAS)
	if (rotation!=180):
		im = im.rotate(360-rotation)
	buf= io.StringIO()
	#im.save(buf, format= 'JPEG')
	out = watermark.watermark(im, mark, "scale", 0.4)
	out.save(buf, format='JPEG')
	return buf.getvalue()
Exemple #5
0
    def __doit(self):
        if not self.__watermark.get():
            messagebox.showerror(message='请输入水印文本')
            return
        try:
            int(self.__watermark_count.get())
        except Exception as e:
            messagebox.showerror(message='不是标准的自然数')
            return

        if self.__watermark_count.get() <= 0:
            messagebox.showerror(message='文件为零不工作')
            return
        if self.__watermark_count.get() > self.__total:
            messagebox.showerror(message='大于文件总量')
            return

        log.log('开始添加水印')
        self.__is_doing = True
        self.__win.protocol("WM_DELETE_WINDOW", self.close)
        self.__ui_frame.pack_forget()
        self.__ui_doing.pack()
        self.__pool = multiprocessing.Pool(
            processes=multiprocessing.cpu_count())
        watermark.undo(dir=self.__dir)
        log.log('水印线程数量 %d' % multiprocessing.cpu_count())
        try:
            watermark.watermark(dir=self.__dir,
                                watermark=self.__watermark.get(),
                                pool=self.__pool,
                                count=self.__watermark_count.get())
        except Exception as e:
            log.log('错误 %s' % e)
        self.__ui_frame.pack()
        self.__ui_doing.pack_forget()
        self.__is_doing = False
Exemple #6
0
def test_defaults():
    a = watermark.watermark()
    txt = a.split('\n')
    clean_txt = []
    for t in txt:
        t = t.strip()
        if t:
            t = t.split(':')[0]
            clean_txt.append(t.strip())
    clean_txt = set(clean_txt)

    expected = [
        'Last updated', 'Python implementation', 'Python version',
        'IPython version', 'Compiler', 'OS', 'Release', 'Machine', 'Processor',
        'CPU cores', 'Architecture'
    ]

    for i in expected:
        assert i in clean_txt, print(f'{i} not in {clean_txt}')
Exemple #7
0
def watermark_image(fileName):
    fileNamePath = TEMP_ROOT_PATH + fileName    
    im = Image.open(fileNamePath)
    watermark_image_path = os.path.join(current_file_path, "watermark.png")
    mark = Image.open(watermark_image_path)
    out = watermark.watermark(im, mark, 'center', 0.6)
    print "**********finish water mark"     
    name = fileName.split('.')
    outFileName = name[0] + '-watermark.' + name[1]
    outFilePath = TEMP_ROOT_PATH + outFileName    
    
    if out:
        out = out.convert('RGB')
        out.save(outFilePath)
        
    else:
        print "Sorry, Save watermarked file Failed."
        
    return outFileName
def capture_loop():
	#check(gp.gp_camera_init(cam, ctx)) #initializes the camera - maybe should be outside of function
	#print '** camera connected' 
	#end_time = time.time() + float(time_sec)
	global e    
	end_time = time.time() + 3.0
	cnt = 0 
	cur_time = 0. 
	start_time = time.time()
	while cur_time < end_time: 
		cnt+=1
		pic = cnt % 3 + 1
		display(preview_capt(), end_time-cur_time)
		#display("img%s.jpg" % pic, end_time-cur_time) #used when not hooked up to camera
		cur_time = time.time() 
	print 'total frames = %s, time = %s' % (cnt, (end_time - start_time))
	email = e.get()

	#trying to capture full size image, but it only comes out as a preview sized image
	gp.gp_camera_capture(cam, fil, ctx)
	cData = ctypes.c_void_p()
	cLen = ctypes.c_ulong()
	gp.gp_file_get_data_and_size(fil, ctypes.byref(cData), ctypes.byref(cLen))
	full_string = ctypes.string_at(cData.value, cLen.value) 
	full_size = Image.open(StringIO.StringIO(full_string))
	mark = Image.open('logo.png')
	full_size = watermark.watermark(full_size, mark, (.70, .70), .3, 1.0)
	#full_size.show() #test to make sure that the image is being captured
	full_size.save('%s.jpg' % email)
	#wait for file to write (not sure if this is necessary)
	write_delay  = 1.0 + time.time()
	while cur_time < write_delay: 
		cur_time = time.time() 
	os.system('echo "Sending an attachment." | mutt -s "attachment" %s -a /home/pi/projects/photobooth/%s.jpg' % (email, email))
	#test print to make sure the formatting is correct, it appears to be
	print 'echo "Sending an attachment." | mutt -s "attachment" %s -a /home/pi/projects/photobooth/%s.jpg' % (email, email)
    # Adjust vref of ADC with the value stored in NVRAM memory if available (see script in 'Calibrate ADC' script folder)
    vrefmV=pycom.nvs_get('vref_mV')
    if vrefmV==None : # when no value is stored
        adc.vref(1100) # new functionality in ADC, works in release '1.10.2.b1’ but not in older releases!
        print("ADC vref set to default value 1100 mV because no value was stored in NVRAM memory of board")
    elif vrefmV<900 or vrefmV>1300 : # when value is out of range
        adc.vref(1100) # same
        print("ADC vref set to default value 1100 mV")
        print("because vrefmV from NVRAM is equal to %6.0f" % vrefmV,"mV (that is outside [900,1300])")
    else :
        adc.vref(vrefmV) # same
        print("ADC vref set to %6.0f" % vrefmV,"mV (data that was stored in NVRAM of board)")

    # Set up watermark sensors (each sensor requires two analog and two digital pins)
    #
    watermark1=watermark.watermark(adc=adc,apin1='P13',apin2='P14',dpin1=Pin('P12'),dpin2=Pin('P11'),r1ohms=6810,r2ohms=6810)
    watermark2=watermark.watermark(adc=adc,apin1='P15',apin2='P16',dpin1=Pin('P10'),dpin2=Pin('P9' ),r1ohms=6810,r2ohms=6810)
    watermark3=watermark.watermark(adc=adc,apin1='P17',apin2='P18',dpin1=Pin('P3' ),dpin2=Pin('P22'),r1ohms=6810,r2ohms=6810)


    wm1kohm=watermark1.read(n=10)/1000  # read 10 times to get a stable value; divide by 1000 to convert ohm >> kohm
    kPa1=watermark.ShockkPa(wm1kohm,soilTempCelsius) # calibration Shock et al. (1989)
    print("watermark 1: Resistance (kohms) = %6.3f" % wm1kohm," Water potential (kPa) = %8.2f" % kPa1)

    wm2kohm=watermark2.read(n=10)/1000
    kPa2=watermark.ShockkPa(wm2kohm,soilTempCelsius)
    print("watermark 2: Resistance (kohms) = %6.3f" % wm2kohm," Water potential (kPa) = %8.2f" % kPa2)

    wm3kohm=watermark3.read(n=10)/1000
    kPa3=watermark.ShockkPa(wm3kohm,soilTempCelsius)
    print("watermark 3: Resistance (kohms) = %6.3f" % wm3kohm," Water potential (kPa) = %8.2f" % kPa3)
Exemple #10
0
    def createMapImage(self):
        import settings
        # Create a map object
        outputMap = mapscript.mapObj(settings.PRIVATE_MAPFILE)
        gd =  mapscript.outputFormatObj('AGG/PNG')
        outputMap.setOutputFormat(gd)
        extent = self.fields['oldata']['extent']
        outputMap.setExtent(extent['left'], extent['bottom'], extent['right'], extent['top'])
        outputMap.setSize(self.W,self.H)
        
        # Set all the layers initially off.
        i=0
        layer = outputMap.getLayer(i)
        while layer:
            layer.status = mapscript.MS_OFF
            i = i + 1
            layer = outputMap.getLayer(i)
        
        connection = "user=%s dbname=%s host=%s password=%s" % (
                            settings.DATABASE_USER,
                            settings.DATABASE_NAME,
                            (settings.DATABASE_HOST or "localhost"),
                            settings.DATABASE_PASSWORD
                        )

        # Example for WMS layer building
        layers = self.fields['oldata']['mapLayers']
        layerNames = ""
        for i,layer in enumerate(layers):
            subLayers = layer['params']['LAYERS']
            if subLayers and (type(subLayers) != types.ListType):
                subLayers = list(subLayers)
            for subLayer in subLayers:
                mapFileLayer = outputMap.getLayerByName(subLayer)
                
                # use layer from mapfile directly.
                if mapFileLayer:
                    # authenticate db connections.
                    if "user=%s" % settings.DATABASE_USER in mapFileLayer.connection:
                        mapFileLayer.connection = connection
                        mapFileLayer.status = mapscript.MS_DEFAULT
                    outputMap.insertLayer(mapFileLayer)
                # generate a custom layer dynamically.
                else:
                    wmsLayer = mapscript.layerObj()
                    wmsLayer.name = 'wms'+str(i)
                    wmsLayer.connection = layer['url'].replace("..",settings.HOST)
                    wmsLayer.connectiontype = mapscript.MS_WMS
                    wmsLayer.status = mapscript.MS_DEFAULT
                    wmsLayer.type = mapscript.MS_LAYER_RASTER
                    #wmsLayer.setProjection("init="+layer['params']['SRS'])
                    # By default take the first 'list' of any values
                    wmsLayer.metadata.set("wms_name", subLayer)
                    wmsLayer.metadata.set("wms_exceptions_format", "application/vnd.ogc.se_xml")
                    wmsLayer.metadata.set("wms_format", "image/png") #layer['params']['FORMAT'])
                    wmsLayer.metadata.set("wms_srs", layer['params']['SRS'])
                    wmsLayer.metadata.set("wms_server_version", layer['params']['VERSION'])
                    outputMap.insertLayer(wmsLayer)
                                    
        vectorLayers = self.fields['oldata']['vectorLayers']
        if len(vectorLayers) > 0:
            dataString = "poly from (select id, poly from referrals_referralshape where "
            for i,vectorLayer in enumerate(vectorLayers):
                if i == 0:
                    dataString = dataString + "id=" + str(vectorLayer)
                else:
                    dataString = dataString + " OR id=" + str(vectorLayer)
            dataString = dataString + ") as foo using unique id using SRID=3005"
            userShapeLayer = outputMap.getLayerByName("user_shapes")
            userShapeLayer.connection = connection
            userShapeLayer.status = mapscript.MS_DEFAULT
            outputMap.insertLayer(userShapeLayer)
            userShapeLayer.data = dataString

        scalebarBG = mapscript.colorObj(255,255,255)
        outputMap.scalebar.status = mapscript.MS_EMBED
        outputMap.scalebar.outlinecolor = scalebarBG

        # Setup the default name for the output image
        # create a subdirectory in tmp in case it already isn't there (to keep it nice a tidy)
        os.popen("mkdir -p /tmp/terratruth_print_files").read()
        
        outputImageFile = '/tmp/terratruth_print_files/testmap%s.jpg'%time.time()
        # Save the image to temporary spot, in jpeg format (PNG was causing an error)
        outputMap.selectOutputFormat('JPEG')
        img = outputMap.draw()
        
        # save and reload because otherwise we don't have a real PIL image apparently.
        img.save(outputImageFile)
        img = Image.open(outputImageFile)
        
        if self.fields.get('confidential'):
            confImage = Image.open(os.path.join(settings.BASE_DIR,"media","images","confidential.gif"))
            img = watermark.watermark(img, confImage, (0, 0), 0.5)
        
        if self.fields.get('legendimages'):
            legend = self.createLegendImage()
            img = watermark.watermark(img, legend,(img.size[0]-legend.size[0],
                0), 1)
        
        img.save(outputImageFile)
        # Can use the outputImageFile to pass back to be inserted into PDF
        # Can return the outputImageUrl that contains the URL to image

        image = ImageReader(outputImageFile)
        return image
Exemple #11
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import os
import pandas as pd
import ray
import ray.rllib.agents.ppo as ppo
import shutil
import sys
import watermark

print(watermark.watermark())


checkpoint_root = "tmp/ppo/cart"
shutil.rmtree(checkpoint_root, ignore_errors=True, onerror=None)

ray_results = f'{os.getenv("HOME")}/ray_results/'
shutil.rmtree(ray_results, ignore_errors=True, onerror=None)

info = ray.init(ignore_reinit_error=True)


SELECT_ENV = "CartPole-v1"
N_ITER = 10

config = ppo.DEFAULT_CONFIG.copy()
config["log_level"] = "WARN"

config["num_workers"] = 1
Exemple #12
0
import os
import watermark

# pdf_one = watermark.watermark("/home/knn/Desktop/pdf_digital_watermark1/sample/trial.portre.0.1.pdf")
pdf_two = watermark.watermark(
    "/home/knn/Desktop/pdf_digital_watermark1/sample/trial.landscape.0.1.pdf",
    "A4")

pdf_two._test()
Exemple #13
0
def add_mark():
    watermark(image_path, text.get())