def load(self,create_mipmap = True): if self.tex_file == None: print "Error: No texture file image set" return False self.location = glGenTextures(1) glBindTexture(GL_TEXTURE_2D,self.location) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,wrap_s) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,wrap_t) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,mag_filter) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,min_filter) # glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, # max_anisotropy) try: im = ImageOps.flip(Image.open(self.tex_file).convert('RGB')) except IOError: print "Error opening file", self.tex_file exit(-1) texdata = im.getdata() buf = numpy.array(texdata,dtype='uint8',order='C') buf_shape = (im.size[0],im.size[1],3) data = numpy.reshape(buf,buf_shape,order='C') glTexImage2Dub(GL_TEXTURE_2D, 0, 3, 0, GL_RGB, data) if self.create_mipmap: glGenerateMipmap(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D,0) return True
def load(self, create_mipmap=True): if self.tex_file == None: print "Error: No texture file image set" return False self.location = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, self.location) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,wrap_s) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,wrap_t) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,mag_filter) # glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,min_filter) # glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, # max_anisotropy) try: im = ImageOps.flip(Image.open(self.tex_file).convert('RGB')) except IOError: print "Error opening file", self.tex_file exit(-1) texdata = im.getdata() buf = numpy.array(texdata, dtype='uint8', order='C') buf_shape = (im.size[0], im.size[1], 3) data = numpy.reshape(buf, buf_shape, order='C') glTexImage2Dub(GL_TEXTURE_2D, 0, 3, 0, GL_RGB, data) if self.create_mipmap: glGenerateMipmap(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, 0) return True
def main(argv): parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--mirror-x', action='store_true') parser.add_argument('--mirror-y', action='store_true') parser.add_argument('--no-display', action='store_false', dest='display') parser.add_argument('--no-click', action='store_false', dest='clicks') args = parser.parse_args(argv[1:]) am = AutoMeta() print "Getting images..." pos, im1, im2 = get_images(am) if args.mirror_x: im2 = ImageOps.mirror(im2) if args.mirror_y: im2 = ImageOps.flip(im2) print "got" print "Aligning..." pix = get_difference_image(im1, im2) print "done" print "Finding differences...", diffs = get_difference_spots(pix) print "done" if args.clicks: # TODO: if two diffs are very close, only click one for diff in diffs: am.move_mouse(pos[0] + diff[1], pos[1] + diff[0]) time.sleep(.1) am.left_click() if args.display: Image.fromarray(pix).show()
def main(): i=0 while(True): try: ppm=StringIO(read_one_ppm(sys.stdin)) im=Image.open(ppm) #encode.encode(im, bool(i%2)) im2=ImageOps.flip(im) tmpo=StringIO() im2.save(tmpo,"PPM") if DEBUG: ppm.seek(0) f=file("/tmp/source-%i.ppm" % i,"wb") f.write(ppm.read()) f.close() tmpo.seek(0) f=file("/tmp/output-%i.ppm" % i,"wb") f.write(tmpo.read()) f.close() ppm.seek(0) tmpo.seek(0) sys.stdout.write(tmpo.read()) sys.stdout.flush() #Must flush each frame if DEBUG: sys.stderr.write("Wrote frame %i\n" % i) i+=1 except NoMorePPM, e: time.sleep(0.01) # Handle empty buffer
def main(): i = 0 while (True): try: ppm = StringIO(read_one_ppm(sys.stdin)) im = Image.open(ppm) #encode.encode(im, bool(i%2)) im2 = ImageOps.flip(im) tmpo = StringIO() im2.save(tmpo, "PPM") if DEBUG: ppm.seek(0) f = file("/tmp/source-%i.ppm" % i, "wb") f.write(ppm.read()) f.close() tmpo.seek(0) f = file("/tmp/output-%i.ppm" % i, "wb") f.write(tmpo.read()) f.close() ppm.seek(0) tmpo.seek(0) sys.stdout.write(tmpo.read()) sys.stdout.flush() #Must flush each frame if DEBUG: sys.stderr.write("Wrote frame %i\n" % i) i += 1 except NoMorePPM, e: time.sleep(0.01) # Handle empty buffer
def output_to_file(self, filename): newstuff = glReadPixels(0, 0, (self.width*2/3), self.height, GL_RGB, GL_UNSIGNED_BYTE) # print len(newstuff) #Insert something to draw to bitmap newimage = Image.frombuffer("RGB", ((self.width*2/3), self.height), newstuff, "raw", "RGB", 0, 0) newimageFlipped = ImageOps.flip(newimage) newimageFlipped.save(filename)
def render(meshes, fileName, wireFrame=False): global initialized, SIZE assert initialized glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) for mesh in meshes: glPolygonMode(GL_FRONT_AND_BACK, (GL_LINE if wireFrame else GL_FILL)) glPushMatrix() # apply transformations glColor3f(*mesh.getColor()) glTranslatef(*mesh.getTranslation()) glScalef(*mesh.getScale()) glRotatef(mesh.getRotation()[2], 0, 0, 1) glRotatef(mesh.getRotation()[1], 0, 1, 0) glRotatef(mesh.getRotation()[0], 1, 0, 0) # send triangles glBegin(GL_TRIANGLES) for triangle in mesh.getTriangles(): for vertex in triangle: glVertex3f(vertex[0], vertex[1], vertex[2]) glEnd() glPopMatrix() glFlush() glutSwapBuffers() # save the framebuffer to disk data = glReadPixels(0, 0, SIZE[0], SIZE[1], GL_RGB, GL_BYTE) img = Image.frombuffer('RGB', SIZE, data, 'raw', 'RGB') flipped = ImageOps.mirror(ImageOps.flip(img)) flipped.save(fileName)
def output_to_file(self, filename): newstuff = glReadPixels(0, 0, (self.width * 2 / 3), self.height, GL_RGB, GL_UNSIGNED_BYTE) # print len(newstuff) #Insert something to draw to bitmap newimage = Image.frombuffer("RGB", ((self.width * 2 / 3), self.height), newstuff, "raw", "RGB", 0, 0) newimageFlipped = ImageOps.flip(newimage) newimageFlipped.save(filename)
def make_thumbnail(data, mode='silloette', npts=500, ar=.15, show=False, **kwargs): y = int(round(npts * ar)) w = npts / 100 #plt.rc('axes', linewidth=0) f = plt.figure(11, figsize=(w, w * ar), dpi=100) plt.subplot(111, frameon=False) THUMBS[mode](data, npts, **kwargs) a = f.get_axes()[0] a.xaxis.set_visible(False) a.yaxis.set_visible(False) f.subplots_adjust(left=0, right=1, bottom=0, top=1) f.canvas.draw() s = StringIO.StringIO() f.savefig(s, format=kwargs.get('format', 'png')) s.seek(0) open('test.pdf', 'wb').write(s.read()) s.seek(0) im = ImageOps.flip(Image.open(s)) if not show: plt.close() return im
def drawmask(self, maskarray, colour=128): """ I draw a mask on the image. Give me a numpy "maskarray" of same size as mine, and I draw on the pilimage all pixels of the maskarray that are True in the maskcolour. By default, colour is gray, to avoid switching to RGB. But if you give for instance (255, 0, 0), I will do the switch. """ self.checkforpilimage() self.changecolourmode(colour) self.makedraw() # Checking size of maskarray : if maskarray.shape[0] != self.pilimage.size[0] or maskarray.shape[ 1] != self.pilimage.size[1]: raise RuntimeError, "Mask and image must have the same size !" # We make an "L" mode image out of the mask : tmparray = np.zeros(maskarray.shape, dtype=np.uint8) tmparray[maskarray] = 255 maskpil = imop.flip(im.fromarray(tmparray.transpose())) # We make a plain colour image : if type(colour) == type(0): plainpil = im.new("L", self.pilimage.size, colour) else: plainpil = im.new("RGB", self.pilimage.size, colour) # We switch self to RGB if needed : self.changecolourmode(colour) # And now use the function composite to "blend" our image with the plain colour image : self.pilimage = im.composite(plainpil, self.pilimage, maskpil) # As we have changed the image object, we have to rebuild the draw object : self.draw = None
def draw_graph(list1, jpeg='probability_graph.jpg'): # height and width of jpeg w, h = 0, 0 for a in range(len(list1)): if list1[a][0] > w: w = list1[a][0] if list1[a][1] > h: h = list1[a][1] # Draw graph and save image img = Image.new('RGB', (w + 45, h + 45), (255, 255, 255)) draw = ImageDraw.Draw(img) for a in range(len(list1) - 1): xycoords = (list1[a][0] + 20, list1[a][1] + 10) x1y1coords = (list1[a][0] + 20, 10) draw.line([xycoords, x1y1coords], fill=128) del draw img = ImageOps.flip(img) draw = ImageDraw.Draw(img) for a in range(0, h, 50): if a == 0: b = str(a) else: b = str(a / 500.0) draw.text((0, h - a + 28), b, fill=0) for a in range(0, w, 25): draw.text((a + 18, h + 35), str(a), fill=0) del draw img.save(jpeg, 'JPEG')
def run(self): while True: # for each document waiting on our input port for doc in self.receive_all('in'): try: # grab the serialized image raw_image = doc.get('image_data') # grab the meta-data we need size = doc.get_meta('size', 'image_data') mode = doc.get_meta('mode', 'image_data') # deserialize the image content image = Image.fromstring(mode, size, raw_image) # perform the flip flipped_image = ImageOps.flip(image) # update the meta-data for the image doc.set_meta('size', flipped_image.size, 'image_data') doc.set_meta('mode', flipped_image.mode, 'image_data') # update the image_data with the new serialized payload doc.set('image_data', flipped_image.tostring()) except Exception as e: log.error('Component Failed: %s' % self.__class__.__name__) log.error('Reason: %s' % str(e)) log.debug(traceback.print_exc()) # send the document to the next component self.send('out', doc) # yield the CPU, allowing another component to run self.yield_ctrl()
def drawmask(self, maskarray, colour = 128): """ I draw a mask on the image. Give me a numpy "maskarray" of same size as mine, and I draw on the pilimage all pixels of the maskarray that are True in the maskcolour. By default, colour is gray, to avoid switching to RGB. But if you give for instance (255, 0, 0), I will do the switch. """ self.checkforpilimage() self.changecolourmode(colour) self.makedraw() # Checking size of maskarray : if maskarray.shape[0] != self.pilimage.size[0] or maskarray.shape[1] != self.pilimage.size[1]: raise RuntimeError, "Mask and image must have the same size !" # We make an "L" mode image out of the mask : tmparray = np.zeros(maskarray.shape, dtype=np.uint8) tmparray[maskarray] = 255 maskpil = imop.flip(im.fromarray(tmparray.transpose())) # We make a plain colour image : if type(colour) == type(0) : plainpil = im.new("L", self.pilimage.size, colour) else : plainpil = im.new("RGB", self.pilimage.size, colour) # We switch self to RGB if needed : self.changecolourmode(colour) # And now use the function composite to "blend" our image with the plain colour image : self.pilimage = im.composite(plainpil, self.pilimage, maskpil) # As we have changed the image object, we have to rebuild the draw object : self.draw = None
def flip(self): self.img = ImageOps.flip(self.img) self.update()
def flip(img_list): for img in img_list: tmp_img = ImageOps.flip(img) yield tmp_img
def generatePlate(plateName, maxLevel): if not os.path.exists("results"): os.system("mkdir results") if not os.path.exists("results/%d" % maxLevel): os.system("mkdir results/%d" % maxLevel) if not os.path.exists("tmp"): os.system("mkdir tmp") print "-------- " + plateName + " --------" if os.path.exists("results/%s.stamp" % (plateName)): print "Plate %s already processed" % (plateName) return assert os.path.exists("preparedPlates") assert os.path.exists("preparedPlates/%s/%s.jpg" % (plateName, plateName)) print "Get list of TOAST tiles intersecting the plate" wcs = dssUtils.DssWcs(plateName) # And make sure to get rid of the plate edges in the corner.. #points = dssUtils.getValidRegionForPlate(plateName) points = [[0,0], [19200, 0], [19200, 19200], [0, 19200]] plateCornersRaDec = [wcs.pixelToRaDec(p) for p in points] cmd = './toastForShape %d "' % (maxLevel) + json.dumps(plateCornersRaDec).replace('"', '\\"') + '"' print cmd p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) jsonTriangles = p.stdout.read() triangles = json.loads(jsonTriangles) print "Convert the pixel position of the toast tiles into the existing DSS image" allTrianglesRadecPos = [] for tri in triangles: allTrianglesRadecPos.extend(tri['tile'][1:]) allTrianglesPixelPos = [wcs.raDecToPixel(p) for p in allTrianglesRadecPos] # Put all contained triangles (to be cut) in the tiles dict tiles = {} i=0 for tri in triangles: tile = allTrianglesPixelPos[i*4:i*4+4] t = {'XY': [tri['i'], tri['j']], 'tile': tile} tiles[json.dumps(t['XY'])]=t i=i+1 tiles = tiles.values() print "Cut and save the toast tiles (%d tiles at level %s)." % (len(tiles), maxLevel) # Create the sub directories os.system("mkdir tmp/%s" % plateName) os.system("mkdir tmp/%s/%d" % (plateName, maxLevel)) print "load full plate image" resImg = Image.open("preparedPlates/%s/%s.jpg" % (plateName, plateName)) #draw = ImageDraw.Draw(resImg) #font = ImageFont.truetype("DejaVuSans.ttf", 600) #draw.text([9500, 9500], plateName, font=font, fill=(255,255,0)) resImg = ImageOps.flip(resImg) def raDecToMellinger(raDec): return [(-raDec[0]/360.+0.5)*mellingerImage.size[0], (-raDec[1]/180.+0.5)*mellingerImage.size[1]] # Generate a low res reference image from Mellinger data delta = 19200./256. referenceImage = Image.new("RGB", (256, 256)) #pix = referenceImage.load() #for i in range(256): # for j in range(256): # raDec = wcs.pixelToRaDec((i*delta+delta/2, j*delta+delta/2)) # if raDec[0]>180: # raDec[0]=raDec[0]-360 # mellingerPos = raDecToMellinger(raDec) # pix[i, j] = mellingerImagePix[mellingerPos[0], mellingerPos[1]] # Enhance plate resImg = dssUtils.enhancePlate(plateName, resImg, referenceImage) def isPartial(imageW, imageH, region): for i in range(len(region)/2): p = [region[i*2], region[i*2+1]] if p[0]<0 or p[0]>imageW or p[1]<0 or p[1]>imageH: return True return False print "Cut tiles" for tile in tiles: tt = [] partial = False for p in tile['tile']: x=p[0] y=p[1] tt.append(x) tt.append(y) tt = tt[6:]+tt[0:6] partial = isPartial(resImg.size[0], resImg.size[1], tt) im = resImg.transform((256,256), Image.QUAD, tuple(tt), Image.BILINEAR) xy = tile['XY'] im.save("tmp/%s/%d/%d_%d%s.jpg" % (plateName, maxLevel, xy[0], xy[1], "-partial" if partial else ""), quality=95) print "package and store results" os.system("mv tmp/%s/%d/* results/%d/" % (plateName, maxLevel, maxLevel)) os.system("rm -rf tmp/%s" % plateName) os.system("touch results/%s.stamp" % plateName)
def render(imageToRender,xOffset,yOffset,w=128,h=64,nocrop=False, overlayBottom=False): global imageTop, imageBottom, screenHeight, screenWidth, panels, matrix, image, renderImage, tileSize, rows, cols, transWiring #w = screenWidth #h = screenHeight segmentImage = [] # the rendered image is the screen size #renderImage = Image.new("RGBA", (screenWidth , 32)) if(nocrop == True) : for n in range(0,rows) : segmentWidth = tileSize[1] * cols segmentHeight = 32 xPos = n * segmentWidth - xOffset yPos = n * 32 #- yOffset segment = imageToRender.crop((0, yPos, segmentWidth, segmentHeight + yPos)) renderImage.paste(segment, (xPos,0,segmentWidth + xPos,segmentHeight)) elif (nocrop == False) : segmentWidth = tileSize[1] * cols segmentHeight = 32 #yOffset = 10 #xOffset = 100 # Must crop exactly the overlap and position of the to-be-rendered image with each segment # ________________ # | | # | | # | ||||||||| | # -----|||||||||--- # | ||||||||| | # | ||||||||| | cropP1 = [0,0] cropP2 = [0,0] for n in range(0,rows) : # Crop PLACEMENTS\ a = max(0, xOffset) + segmentWidth * n b = max(0, yOffset - segmentHeight * n) c = min(segmentWidth, xOffset + w) + segmentWidth * n d = min(segmentHeight, yOffset + h - segmentHeight * n) # Cropping cropP2 = [ cropP1[0] + c - xOffset, cropP1[1] + min(32, d - yOffset + n * segmentHeight)] cropP1 = [max(0 , 0 - xOffset), max(0, n * segmentHeight - yOffset)] cropP2 = [min(w , segmentWidth - xOffset), min(h, n * segmentHeight + 32 - yOffset)] pCrop = cropP1 + cropP2 if ((n==0 or n == 2 or n == 4) and (transWiring == False) ) : pCrop[1] = 0 segmentImage.append(imageToRender.crop(pCrop)) #print(a,b,c,d,cropP1,cropP2) # Depending on the cabling, either copy segment laterally - which I think # is faster, or transform the segment each time to flip and mirror because # the panels are upside down wrt the ones below them # Wiring from BACK **** = ribbon jumper cables # ________________ # | | # | <-- * | # | | * | # --------------*-- # | * | # | ^ * | # | |--> | # ________________ # ________________ # | ^ | # | * |--> | # | * | # --------*-------- # | * | # | ^ * | # | |--> | # ________________ # Only render if needs be if(pCrop[3] - pCrop[1] > 0 ) : if ( pCrop[2] - pCrop[0] > 0) : segImg = segmentImage[n] if ((n==0 or n == 2 or n == 4) and (transWiring == False) ) : # This flips, reveses and places the segment when the row is "upside down" wrt # the previous row of panels - this is when transWiring == False - i.e no long transverse cable segImg = ImageOps.flip(segImg) segImg = ImageOps.mirror(segImg) an = segmentWidth - xOffset - w if(an < 0) : an = 0 bn = segmentHeight - yOffset - h if(bn < 0) : bn = 0 renderImage.paste( segImg, (an, bn, an + pCrop[2] - pCrop[0], bn + pCrop[3] - pCrop[1])) else: renderImage.paste( segImg, (a, b, a + pCrop[2] - pCrop[0], b + pCrop[3] - pCrop[1])) cropP1[1] = cropP2[1] if(overlayBottom) : renderImage = Image.new("RGBA", (w , h)) renderImage.paste(imageToRender, (0,0)) iid = renderImage.im.id idtemp = image.im.id matrix.SetImage(iid, xOffset + screenWidth, 0) else : iid = renderImage.im.id idtemp = image.im.id matrix.SetImage(iid, 0, 0)
for i in f : uvIds.append(int(i)) uvCounts = om.MIntArray() for c in range(0,len(faces),1): uvCounts.append(int(len(f))) meshnode.assignUVs(uvCounts,uvIds) print("TIME ",time.time() -t1) listecolor = numpy.array(listecolor) for l in range(100): colour = (0, 0, 255 * l / 100) imdraw.line((0, l, 100, l), fill=colour)#line are xy->xy del imdraw import ImageOps im=Image.open("/Users/ludo/uv.png") imo=ImageOps.mirror(im) im=ImageOps.flip(imo) im.save("/Users/ludo/uv.png") #53 #56 #75 #C4D # tag.SetSlow(i, c4d.Vector((x+2)/sizex,(y+2)/sizey,0), # c4d.Vector((x+s-2)/sizex,(y+s-2)/sizey,0), # c4d.Vector((x+s-2)/sizex,(y+2)/sizey,0), # c4d.Vector((x+s-2)/sizex,(y+2)/sizey,0)) x=0 y=0 s=20 u = om.MFloatArray(len(vertices)) v = om.MFloatArray(len(vertices)) #meshnode.setUVs(u,v)
def horizontal_symmetry(digit, features, prefix=''): width,height = digit.image.size first_half = numpy.array(digit.image.crop((0, 0, width, height/2)).getdata()) second_half = numpy.array(ImageOps.flip(digit.image.crop((0, height/2, width, height))).getdata()) second_half = second_half[:len(first_half)] features[prefix+'horizontal_symmetry'] = numpy.linalg.norm(first_half-second_half)
def generatePlate(plateName, maxLevel): if not os.path.exists("results"): os.system("mkdir results") if not os.path.exists("results/%d" % maxLevel): os.system("mkdir results/%d" % maxLevel) if not os.path.exists("tmp"): os.system("mkdir tmp") print "-------- " + plateName + " --------" if os.path.exists("results/%s.stamp" % (plateName)): print "Plate %s already processed" % (plateName) return assert os.path.exists("preparedPlates") assert os.path.exists("preparedPlates/%s/%s.jpg" % (plateName, plateName)) print "Get list of TOAST tiles intersecting the plate" wcs = dssUtils.DssWcs(plateName) # And make sure to get rid of the plate edges in the corner.. #points = dssUtils.getValidRegionForPlate(plateName) points = [[0, 0], [19200, 0], [19200, 19200], [0, 19200]] plateCornersRaDec = [wcs.pixelToRaDec(p) for p in points] cmd = './toastForShape %d "' % (maxLevel) + json.dumps( plateCornersRaDec).replace('"', '\\"') + '"' print cmd p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) jsonTriangles = p.stdout.read() triangles = json.loads(jsonTriangles) print "Convert the pixel position of the toast tiles into the existing DSS image" allTrianglesRadecPos = [] for tri in triangles: allTrianglesRadecPos.extend(tri['tile'][1:]) allTrianglesPixelPos = [wcs.raDecToPixel(p) for p in allTrianglesRadecPos] # Put all contained triangles (to be cut) in the tiles dict tiles = {} i = 0 for tri in triangles: tile = allTrianglesPixelPos[i * 4:i * 4 + 4] t = {'XY': [tri['i'], tri['j']], 'tile': tile} tiles[json.dumps(t['XY'])] = t i = i + 1 tiles = tiles.values() print "Cut and save the toast tiles (%d tiles at level %s)." % (len(tiles), maxLevel) # Create the sub directories os.system("mkdir tmp/%s" % plateName) os.system("mkdir tmp/%s/%d" % (plateName, maxLevel)) print "load full plate image" resImg = Image.open("preparedPlates/%s/%s.jpg" % (plateName, plateName)) #draw = ImageDraw.Draw(resImg) #font = ImageFont.truetype("DejaVuSans.ttf", 600) #draw.text([9500, 9500], plateName, font=font, fill=(255,255,0)) resImg = ImageOps.flip(resImg) def raDecToMellinger(raDec): return [(-raDec[0] / 360. + 0.5) * mellingerImage.size[0], (-raDec[1] / 180. + 0.5) * mellingerImage.size[1]] # Generate a low res reference image from Mellinger data delta = 19200. / 256. referenceImage = Image.new("RGB", (256, 256)) #pix = referenceImage.load() #for i in range(256): # for j in range(256): # raDec = wcs.pixelToRaDec((i*delta+delta/2, j*delta+delta/2)) # if raDec[0]>180: # raDec[0]=raDec[0]-360 # mellingerPos = raDecToMellinger(raDec) # pix[i, j] = mellingerImagePix[mellingerPos[0], mellingerPos[1]] # Enhance plate resImg = dssUtils.enhancePlate(plateName, resImg, referenceImage) def isPartial(imageW, imageH, region): for i in range(len(region) / 2): p = [region[i * 2], region[i * 2 + 1]] if p[0] < 0 or p[0] > imageW or p[1] < 0 or p[1] > imageH: return True return False print "Cut tiles" for tile in tiles: tt = [] partial = False for p in tile['tile']: x = p[0] y = p[1] tt.append(x) tt.append(y) tt = tt[6:] + tt[0:6] partial = isPartial(resImg.size[0], resImg.size[1], tt) im = resImg.transform((256, 256), Image.QUAD, tuple(tt), Image.BILINEAR) xy = tile['XY'] im.save( "tmp/%s/%d/%d_%d%s.jpg" % (plateName, maxLevel, xy[0], xy[1], "-partial" if partial else ""), quality=95) print "package and store results" os.system("mv tmp/%s/%d/* results/%d/" % (plateName, maxLevel, maxLevel)) os.system("rm -rf tmp/%s" % plateName) os.system("touch results/%s.stamp" % plateName)
def makepilimage(self, scale = "log", negative = False): """ Makes a PIL image out of the array, respecting the z1 and z2 cutoffs. By default we use a log scaling identical to iraf's, and produce an image of mode "L", i.e. grayscale. But some drawings or colourscales will change the mode to "RGB" later, if you choose your own colours. If you choose scale = "clog" or "clin", you get hue values (aka rainbow colours). """ calcarray = self.numpyarray.transpose() if scale == "log" or scale == "lin": self.negative = negative #numpyarrayshape = self.numpyarray.shape #calcarray.ravel() # does not change in place in fact ! calcarray = calcarray.clip(min = self.z1, max = self.z2) if scale == "log": #calcarray = np.array(map(lambda x: loggray(x, self.z1, self.z2), calcarray)) calcarray = loggray(calcarray, self.z1, self.z2) else : #calcarray = np.array(map(lambda x: lingray(x, self.z1, self.z2), calcarray)) calcarray = lingray(calcarray, self.z1, self.z2) #calcarray.shape = numpyarrayshape bwarray = np.zeros(calcarray.shape, dtype=np.uint8) calcarray.round(out=bwarray) if negative: if self.verbose: print "Using negative scale" bwarray = 255 - bwarray if self.verbose: print "PIL range : [%i, %i]" % (np.min(bwarray), np.max(bwarray)) # We flip it so that (0, 0) is back in the bottom left corner as in ds9 # We do this here, so that you can write on the image from left to right :-) self.pilimage = imop.flip(im.fromarray(bwarray)) if self.verbose: print "PIL image made with scale : %s" % scale return 0 if scale == "clog" or scale == "clin": # Rainbow ! self.negative = False if scale == "clin": calcarray = (calcarray.clip(min = self.z1, max = self.z2)-self.z1)/(self.z2 - self.z1) # 0 to 1 if scale == "clog": calcarray = 10.0 + 990.0 * (calcarray.clip(min = self.z1, max = self.z2)-self.z1)/(self.z2 - self.z1) # 10 to 1000 calcarray = (np.log10(calcarray)-1.0)*0.5 # 0 to 1 (rarray, garray, barray) = rainbow(calcarray, autoscale=False) carray = np.dstack((rarray,garray,barray)) self.pilimage = imop.flip(im.fromarray(carray, "RGB")) if self.verbose: print "PIL image made with scale : %s" % scale return 0 raise RuntimeError, "I don't know your colourscale, choose lin log clin or clog !"
def makepilimage(self, scale="log", negative=False): """ Makes a PIL image out of the array, respecting the z1 and z2 cutoffs. By default we use a log scaling identical to iraf's, and produce an image of mode "L", i.e. grayscale. But some drawings or colourscales will change the mode to "RGB" later, if you choose your own colours. If you choose scale = "clog" or "clin", you get hue values (aka rainbow colours). """ if scale == "log" or scale == "lin": self.negative = negative numpyarrayshape = self.numpyarray.shape calcarray = self.numpyarray.copy() #calcarray.ravel() # does not change in place in fact ! calcarray = calcarray.clip(min=self.z1, max=self.z2) if scale == "log": calcarray = np.array( map(lambda x: loggray(x, self.z1, self.z2), calcarray)) else: calcarray = np.array( map(lambda x: lingray(x, self.z1, self.z2), calcarray)) calcarray.shape = numpyarrayshape bwarray = np.zeros(numpyarrayshape, dtype=np.uint8) calcarray.round(out=bwarray) if negative: if self.verbose: print "Using negative scale" bwarray = 255 - bwarray if self.verbose: print "PIL range : [%i, %i]" % (np.min(bwarray), np.max(bwarray)) # We flip it so that (0, 0) is back in the bottom left corner as in ds9 # We do this here, so that you can write on the image from left to right :-) self.pilimage = imop.flip(im.fromarray(bwarray.transpose())) if self.verbose: print "PIL image made with scale : %s" % scale return 0 if scale == "clog" or scale == "clin": """ rainbow ! Algorithm for HSV to RGB from http://www.cs.rit.edu/~ncs/color/t_convert.html, by Eugene Vishnevsky Same stuff then for f2n in C h is from 0 to 360 (hue) s from 0 to 1 (saturation) v from 0 to 1 (brightness) """ self.negative = False calcarray = self.numpyarray.transpose() if scale == "clin": calcarray = (calcarray.clip(min=self.z1, max=self.z2) - self.z1) / (self.z2 - self.z1) # 0 to 1 if scale == "clog": calcarray = 10.0 + 990.0 * ( calcarray.clip(min=self.z1, max=self.z2) - self.z1) / ( self.z2 - self.z1) # 10 to 1000 calcarray = (np.log10(calcarray) - 1.0) * 0.5 # 0 to 1 #calcarray = calcarray * 359.0 # This is now our "hue value", 0 to 360 calcarray = (1.0 - calcarray ) * 300.0 # I limit this to not go into red again # The order of colours is Violet < Blue < Green < Yellow < Red # We prepare the output arrays rcalcarray = np.ones(calcarray.shape) gcalcarray = np.ones(calcarray.shape) bcalcarray = np.ones(calcarray.shape) h = calcarray / 60.0 # sector 0 to 5 i = np.floor(h).astype(np.int) v = 1.0 * np.ones(calcarray.shape) s = 1.0 * np.ones(calcarray.shape) f = h - i # factorial part of h, this is an array p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) # sector 0: indices = (i == 0) rcalcarray[indices] = 255.0 * v[indices] gcalcarray[indices] = 255.0 * t[indices] bcalcarray[indices] = 255.0 * p[indices] # sector 1: indices = (i == 1) rcalcarray[indices] = 255.0 * q[indices] gcalcarray[indices] = 255.0 * v[indices] bcalcarray[indices] = 255.0 * p[indices] # sector 2: indices = (i == 2) rcalcarray[indices] = 255.0 * p[indices] gcalcarray[indices] = 255.0 * v[indices] bcalcarray[indices] = 255.0 * t[indices] # sector 3: indices = (i == 3) rcalcarray[indices] = 255.0 * p[indices] gcalcarray[indices] = 255.0 * q[indices] bcalcarray[indices] = 255.0 * v[indices] # sector 4: indices = (i == 4) rcalcarray[indices] = 255.0 * t[indices] gcalcarray[indices] = 255.0 * p[indices] bcalcarray[indices] = 255.0 * v[indices] # sector 5: indices = (i == 5) rcalcarray[indices] = 255.0 * v[indices] gcalcarray[indices] = 255.0 * p[indices] bcalcarray[indices] = 255.0 * q[indices] rarray = np.zeros(calcarray.shape, dtype=np.uint8) garray = np.zeros(calcarray.shape, dtype=np.uint8) barray = np.zeros(calcarray.shape, dtype=np.uint8) rcalcarray.round(out=rarray) gcalcarray.round(out=garray) bcalcarray.round(out=barray) carray = np.dstack((rarray, garray, barray)) self.pilimage = imop.flip(im.fromarray(carray, "RGB")) if self.verbose: print "PIL image made with scale : %s" % scale return 0 raise RuntimeError, "I don't know your colourscale, choose lin log clin or clog !"
def array2png(array, filename, ztrans="log", cutoffs=(None, None)): # You need to generate the pilimage first ! import ImageOps, AImage pil = makepilimage(AImage.Image(array.copy()), ztrans, cutoffs) flippilimage = ImageOps.flip(pil) flippilimage.save(filename, "PNG")