def xmlbuffer(self): queryimpl = QXmlQuery(QXmlQuery.XQuery10) #merge params from xquerynames and query path arguments params = copy.deepcopy(self.xquerynames) for name,value in self._queryparams.iteritems(): params.append([name,value]) #push values into external variable names in xquery for item in params: if len(item)==3 : # item has namespace (name,value,namespace) = item qname = QXmlName(queryimpl.namePool(), name, namespace) else: (name,value) = item qname = QXmlName(queryimpl.namePool(), name) qvalue = QXmlItem(value) queryimpl.bindVariable(qname,qvalue) #bind focus if available if(self.focuspath != None): queryimpl.setFocus(QUrl.fromLocalFile(self.focuspath)) queryimpl.setQuery(self.querysource) buf = QBuffer() buf.open(QBuffer.ReadWrite) queryimpl.evaluateTo(buf) buf.close() data = buf.data() return data
def screenshot(self): logging.debug('screenshot() invoked') frame = self.page().mainFrame() size = frame.contentsSize() if (self.screenWidth): size.setWidth(self.screenWidth) if (self.screenHeight): size.setHeight(self.screenHeight) if (self.minWidth and self.minWidth > self.screenWidth): size.setWidth(self.minWidth) if (self.minHeight and self.minHeight > self.screenHeight): size.setHeight(self.minHeight) self.page().setViewportSize(size) image = QImage(self.page().viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) frame.render(painter) painter.end() buffer = QBuffer() buffer.open(QIODevice.ReadWrite) image.save(buffer, self.format, self.quality) logging.debug('screenshot() returned image of type ' + self.content_type + ' of length ' + str(buffer.data().length())) return { 'content': buffer.data(), 'content_type': self.content_type }
def store_data(self, id, data): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height( ) > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def render_image(self): public_rect = self.live_text_rect() #global_rect = QtCore.QRect(self.mapToGlobal(public_rect.topLeft()), self.mapToGlobal(public_rect.bottomRight())) pixmap = QPixmap.grabWindow(self.win_id, public_rect.x() + 1, public_rect.y() + 1, 768, 576) buf = QBuffer() buf.open(QIODevice.WriteOnly) pixmap.save(buf, "JPG", 75) return buf.data()
def QIm2PIL(qimg): buff = QBuffer() buff.open(QIODevice.WriteOnly) qimg.save(buff, 'BMP') fp = StringIO() fp.write(buff.data()) buff.close() fp.seek(0) pilimg = Image.open(fp) if pilimg.mode == 'P': return pilimg.convert('L') return pilimg
def _getPng(self, width=None, height=None): image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.web_page.mainFrame().render(painter) painter.end() if width: image = image.scaledToWidth(width, Qt.SmoothTransformation) if height: image = image.copy(0, 0, width, height) b = QBuffer() image.save(b, "png") return bytes(b.data())
def _render(self): self.setViewportSize(QSize(self.vwidth, self.vheight)) image = QImage(self.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.mainFrame().render(painter) painter.end() if self.width: image = image.scaledToWidth(self.width, Qt.SmoothTransformation) if self.height: image = image.copy(0, 0, self.width, self.height) b = QBuffer() image.save(b, "png") return str(b.data())
def _qimage_to_pil(self, qimage): """ Convert QImage to PIL Image """ ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) qimage.save(bf, 'TIFF', quality=100) bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) return PIL.Image.open(buf)
def OCRperformOCRName(position,x,y,w,h,digits = False): img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h) #img.save('a.png', 'png') buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) im = Image.open(strio) pixdata = im.load(); for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (255, 255, 255) else: pixdata[x, y] = (0, 0, 0) #Add extra space on each side for y in xrange(im.size[1]): pixdata[0,y] = (255, 255, 255) pixdata[1,y] = (255, 255, 255) pixdata[im.size[0]-1,y] = (255, 255, 255) pixdata[im.size[0]-2,y] = (255, 255, 255) for x in xrange(im.size[0]): pixdata[x,0] = (255, 255, 255) pixdata[x,1] = (255, 255, 255) pixdata[x,im.size[1]-1] = (255, 255, 255) pixdata[x,im.size[1]-2] = (255, 255, 255) nx, ny = im.size im = im.resize((nx*5, ny*5), Image.ANTIALIAS) enh = ImageEnhance.Contrast(im) pixdata = im.load() for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR) rvalue = OCR_to_string(im,digits) #im.save("training"+str(position)+""+str(int(random.random()*10000)) +".png","PNG") return rvalue
def _getPng(self, width=None, height=None, b64=False): self.log("getting PNG %s" % id(self.splash_request)) image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.web_page.mainFrame().render(painter) painter.end() self.web_page.har_log.store_timing("_onScreenshotPrepared") if width: image = image.scaledToWidth(width, Qt.SmoothTransformation) if height: image = image.copy(0, 0, width, height) b = QBuffer() image.save(b, "png") result = bytes(b.data()) if b64: result = base64.b64encode(result) self.web_page.har_log.store_timing("_onPngRendered") return result
def png(self, width=None, height=None, b64=False): """ Return screenshot in PNG format """ self.logger.log("getting PNG", min_level=2) image = QImage(self.web_page.viewportSize(), QImage.Format_ARGB32) painter = QPainter(image) self.web_page.mainFrame().render(painter) painter.end() self.store_har_timing("_onScreenshotPrepared") if width: image = image.scaledToWidth(width, Qt.SmoothTransformation) if height: image = image.copy(0, 0, width, height) b = QBuffer() image.save(b, "png") result = bytes(b.data()) if b64: result = base64.b64encode(result) self.store_har_timing("_onPngRendered") return result
def store_data(self, id, data): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') makedirs(directory) pixmap = QPixmap() if data is not None and pixmap.loadFromData(data): image_size = pixmap.size() if image_size.width() > self.max_size or image_size.height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if imghdr.what(None, data) != 'png' or pixmap.size() != image_size: buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def store_file(self, id, file): directory = ApplicationData.get('images') filename = os.path.join(directory, id + '.png') if filename == os.path.normpath(file): return self.iconmap.get(id, None) makedirs(directory) pixmap = QPixmap() if file is not None and pixmap.load(file): if pixmap.size().width() > self.max_size or pixmap.size().height() > self.max_size: pixmap = pixmap.scaled(self.max_size, self.max_size, Qt.KeepAspectRatio, Qt.SmoothTransformation) buffer = QBuffer() pixmap.save(buffer, 'png') data = str(buffer.data()) with open(filename, 'wb') as f: f.write(data) icon = QIcon(pixmap) icon.filename = filename icon.content = data else: unlink(filename) icon = None self.iconmap[id] = icon return icon
def to_png(self, complevel=defaults.PNG_COMPRESSION_LEVEL): quality = 90 - (complevel * 10) buf = QBuffer() self.img.save(buf, 'png', quality=quality) return bytes(buf.data())
def render(self, params): self.check_required_params(params) with change_directory(self.project_root): crs = QgsCoordinateReferenceSystem() crs.createFromSrid(params.get('srs')) img = QImage( QSize(*params.get('image_size')), QImage.Format_ARGB32_Premultiplied ) dpm = 1 / 0.00028 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) # set background color bgcolor = params.get('bgcolor') if params.get('transparent'): # fully transparent bgcolor.append(0) else: # fully opaque bgcolor.append(255) color = QColor(*bgcolor) img.fill(color) map_settings = QgsMapSettings() map_settings.setBackgroundColor(color) map_settings.setDestinationCrs(crs) map_settings.setCrsTransformEnabled(True) map_settings.setExtent(QgsRectangle(*params.get('bbox'))) map_settings.setOutputDpi(img.logicalDpiX()) map_settings.setOutputSize(img.size()) map_settings.setMapUnits(crs.mapUnits()) layers = params.get('layers') self.setTransparencies(layers, params.get('transparencies')) map_settings.setLayers(layers) p = QPainter() p.begin(img) job = QgsMapRendererCustomPainterJob(map_settings, p) job.start() job.waitForFinished() map_buffer = QBuffer() map_buffer.open(QIODevice.ReadWrite) if params.get('image_format') == 'jpeg': img.save(map_buffer, 'JPEG') elif params.get('image_format') == 'png8': png8 = img.convertToFormat(QImage.Format_Indexed8) png8.save(map_buffer, "PNG") else: img.save(map_buffer, 'PNG') # clean up p.end() map_buffer.close() return map_buffer.data()
def getLegendGraphic(self, params): qgsLayer = self.layerRegistry.mapLayer(params.get('layer')) boxSpace = 1 layerSpace = 2 # layerTitleSpace = 3 symbolSpace = 2 iconLabelSpace = 2 symbolWidth = 5 symbolHeight = 3 drawLegendLabel = True rootGroup = QgsLayerTreeGroup() rootGroup.addLayer(qgsLayer) # layer = QgsLayerTreeLayer(qgsLayer) # if qgsLayer.title(): # layer.setLayerName(qgsLayer.title()) legendModel = QgsLayerTreeModel(rootGroup) rootChildren = rootGroup.children() img_tmp = QImage(QSize(1, 1), QImage.Format_ARGB32_Premultiplied) dpm = 1 / 0.00028 img_tmp.setDotsPerMeterX(dpm) img_tmp.setDotsPerMeterY(dpm) dpmm = img_tmp.dotsPerMeterX() / 1000.0 del img_tmp legendSettings = QgsLegendSettings() legendSettings.setTitle('') legendSettings.setBoxSpace(boxSpace) legendSettings.rstyle(QgsComposerLegendStyle.Subgroup).setMargin(QgsComposerLegendStyle.Top, layerSpace) legendSettings.rstyle(QgsComposerLegendStyle.Symbol).setMargin(QgsComposerLegendStyle.Top, symbolSpace) legendSettings.rstyle(QgsComposerLegendStyle.SymbolLabel).setMargin(QgsComposerLegendStyle.Left, iconLabelSpace) legendSettings.setSymbolSize(QSizeF(symbolWidth, symbolHeight)) # legendSettings.rstyle(QgsComposerLegendStyle.Subgroup).setFont(layerFont) # legendSettings.rstyle(QgsComposerLegendStyle.SymbolLabel).setFont(itemFont) # // TODO: not available: layer font color # legendSettings.setFontColor( itemFontColor ); # for node in rootChildren: # if (QgsLayerTree.isLayer(node)): # QgsLegendRenderer.setNodeLegendStyle(node, QgsComposerLegendStyle.Subgroup) # # rule item titles # # if ( !mDrawLegendItemLabel ) # # for legendNode in legendModel.layerLegendNodes(nodeLayer): # # legendNode.setUserLabel(' ') # # } legendRenderer = QgsLegendRenderer(legendModel, legendSettings) minSize = legendRenderer.minimumSize() s = QSize(minSize.width() * dpmm, minSize.height() * dpmm) img = QImage(s, QImage.Format_ARGB32_Premultiplied) # fill in the background color = QColor(0, 0, 0, 0) img.fill(color) p = QPainter() p.begin(img) p.setRenderHint(QPainter.Antialiasing, True) p.scale(dpmm, dpmm) legendRenderer.drawLegend(p) map_buffer = QBuffer() map_buffer.open(QIODevice.ReadWrite) img.save(map_buffer, 'PNG') # clean up map_buffer.close() p.end() # self.layerRegistry.removeAllMapLayers() return map_buffer.data()
def OCRperformOCRPlayerBalance(x,y,w,h,flag = False): rvalue = '' img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h) #img= Image.open('/home/liutauras/Documents/Python/P0.912100785738.png') if(flag): img.save('P'+str(random.random())+'.png', 'png') buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) im = Image.open(strio) #im = Image.open('/home/liutauras/Documents/Python/PtestAllIn.png') pixdata = im.load(); for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 550: pixdata[x, y] = (255, 255, 255) else: pixdata[x, y] = (0, 0, 0) #Add extra space on each side for y in xrange(im.size[1]): pixdata[0,y] = (255, 255, 255) pixdata[1,y] = (255, 255, 255) pixdata[im.size[0]-1,y] = (255, 255, 255) pixdata[im.size[0]-2,y] = (255, 255, 255) for x in xrange(im.size[0]): pixdata[x,0] = (255, 255, 255) pixdata[x,1] = (255, 255, 255) pixdata[x,im.size[1]-1] = (255, 255, 255) pixdata[x,im.size[1]-2] = (255, 255, 255) nx, ny = im.size im = im.resize((nx*5, ny*5), Image.ANTIALIAS) enh = ImageEnhance.Contrast(im) pixdata = im.load() for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR) #rvalue = OCR_to_string(im,True) pixdata = im.load() #Spit by Character totalSumLast = 0 startX = 0 for x in xrange(im.size[0]): #Start of digits flag totalSum = 0 for y in xrange(im.size[1]): totalSum = totalSum + pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if(totalSum < totalSumLast and totalSumLast == 61200): startX = x for y in xrange(im.size[1]): pixdata[x, y] = (0, 0, 0) elif(totalSum > totalSumLast and totalSum == 61200 and startX != 0): #Detect start on y axis flagAllIn = 0 flagSittingOut = 0 startY = 0 for y1 in xrange(im.size[1]): if(flagAllIn == 1 or flagSittingOut == 1): break innerSum = 0 divTot = 0 for x1 in xrange(startX,x): innerSum = innerSum + sum(pixdata[x1, y1]) divTot = divTot + 1 innerSum = innerSum/divTot if(startY == 0 and innerSum < 630): startY = y1 elif(startY != 0 and innerSum > 630): for x1 in xrange(startX,x): pixdata[x1, startY] = (0, 200, 0) pixdata[x1, y1] = (0, 0, 200) #Total area sum totalAreaSum = 0 for x1 in xrange(startX,x): for y2 in xrange(startY,y1): totalAreaSum = totalAreaSum + sum(pixdata[x1, y2]) #Decoding digit if(totalAreaSum == 353945): flagAllIn = 1 rvalue = '0' break elif(totalAreaSum == 105910): rvalue = '-1' flagSittingOut = 1 elif(totalAreaSum == 8285): rvalue = rvalue + ',' elif(totalAreaSum == 230545): rvalue = rvalue + '0' elif(totalAreaSum == 199475): rvalue = rvalue + '1' elif(totalAreaSum == 346825): rvalue = rvalue + '2' elif(totalAreaSum == 362125): rvalue = rvalue + '3' elif(totalAreaSum == 379720): rvalue = rvalue + '4' elif(totalAreaSum == 304750): rvalue = rvalue + '5' elif(totalAreaSum == 295570): rvalue = rvalue + '6' elif(totalAreaSum == 453160): rvalue = rvalue + '7' elif(totalAreaSum == 219070): rvalue = rvalue + '8' elif(totalAreaSum == 310870): rvalue = rvalue + '9' startY = 0 startX = 0 for y in xrange(im.size[1]): pixdata[x, y] = (200, 0, 0) totalSumLast = totalSum rvalue = rvalue.replace('\n','').replace(' ','') if(flag): im.save("Pa"+str(random.random())+".png") rvalue = rvalue.replace(',','').replace(' ','').replace('.','') if(len(rvalue) > 0): return int(rvalue) else: return -2
def do_GET(self): print "get" global plotValues try: self.path = re.sub('[^.a-zA-Z0-9]', "", str(self.path)) if self.path == "" or self.path == None or self.path[:1] == ".": return if self.path.endswith(".html"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() return if self.path.endswith(".mjpeg"): self.thread = WorkThread() #self.thread.osc_received.connect(self.change) #self.connect(self.thread, thread.osc_received, self.change) self.thread.osc_received.connect(self.receive_osc) self.thread.start() self.send_response(200) self.plt = plt = PlotWindow(title="EKG", name="Merle") plt.addLegend() #plt = pg.plot(pen=(0, 3*1.3)) plt.resize(1280, 720) self.plotItem1 = plotItem1 = pg.PlotCurveItem(pen=pg.mkPen( 'r', width=4), name="bjoern") self.plotItem2 = plotItem2 = pg.PlotCurveItem(pen=pg.mkPen( 'g', width=4), name="merle") self.plotItem3 = plotItem3 = pg.PlotCurveItem(pen=pg.mkPen( 'b', width=4), name="uwe") plotItem1.setPos(0, 0 * 6) plotItem2.setPos(0, 1 * 6) plotItem3.setPos(0, 2 * 6) plt.addItem(plotItem1) plt.addItem(plotItem2) plt.addItem(plotItem3) plt.setLabel('left', "EKG") plt.setLabel('bottom', "Time") plt.showGrid(True, True) ba = plt.getAxis("bottom") bl = plt.getAxis("left") ba.setTicks([]) bl.setTicks([]) plt.setYRange(0, 254) #print type(plt) self.wfile.write( "Content-Type: multipart/x-mixed-replace; boundary=--aaboundary" ) self.wfile.write("\r\n\r\n") last = time.time() now = last while 1: plotItem1.setData(y=np.array(self.plot_data1), clear=True) plotItem2.setData(y=np.array(self.plot_data2), clear=True) plotItem3.setData(y=np.array(self.plot_data3), clear=True) #item = plt.plot(plot_data1, pen=(0, 3*1.3), clear=True) exporter = pg.exporters.ImageExporter.ImageExporter( plt.plotItem) exporter.parameters()['width'] = 1280 #exporter.parameters()['height'] = 720 name = 'tmpfile' img = exporter.export(name, True) buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "JPG", 100) JpegData = buffer.data() self.wfile.write("--aaboundary\r\n") self.wfile.write("Content-Type: image/jpeg\r\n") self.wfile.write("Content-length: %d\r\n\r\n" % len(JpegData)) self.wfile.write(JpegData) self.wfile.write("\r\n\r\n\r\n") now = time.time() dur = now - last #print dur wait = 0.04 - dur if wait > 0: time.sleep(wait) last = now return if self.path.endswith(".jpeg"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'image/jpeg') self.end_headers() self.wfile.write(f.read()) f.close() return return except IOError: self.send_error(404, 'File Not Found: %s' % self.path)
class Connection(QTcpSocket): """Abstracts server-client connections. Whenever data is received, a Connection attempts to parse a Message and arguments from the data, and emits messageReceived for each parsed message. See QTcpSocket documentation for other members.""" messageSent = pyqtSignal(int, list) """Emitted whenever a message is sent. Arguments: the message type, list of arguments.""" messageReceived = pyqtSignal(int, list) """Emitted whenever a message is recieved. Arguments: the message type, list of arguments.""" messageReceived2 = pyqtSignal() def __init__(self, id = None, client = False, parent = None): """Creates a connection. id -- Optional socket descriptor. client -- Whether this connection is opened from the client side or server side. parent -- Parent object.""" QTcpSocket.__init__(self, parent) if id: if not self.setSocketDescriptor(id): self.done() return self.id = id self.player = None self.client = client self.buffer = QBuffer() self.buffer.open(QBuffer.ReadWrite) self.readyRead.connect(self._readIncomingData) def abort(self): """Aborts the connection.""" super(Connection, self).abort() def _readIncomingData(self): bytesWritten = self.buffer.write(self.readAll()) self.buffer.seek(0) result = self._parse() bytesRead = 0 while result: bytesRead += result[2] msg, args = result[:2] if self.client: log.debug("Received %s %s", msg, args) elif self.player and self.player.name: log.debug("Received %s %s from %s", msg, args, self.player) else: log.debug("Received %s %s from %s", msg, args, self.peerAddress().toString()) self.messageReceived.emit(msg, args) self.messageReceived2.emit() result = self._parse() #remove the successfully parsed data size = self.buffer.size() self.buffer.close() data = self.buffer.data() self.buffer.setData(data.right(size - bytesRead)) self.buffer.open(QBuffer.ReadWrite) self.buffer.seek(self.buffer.size()) def _parse(self): if self.buffer.bytesAvailable() >= 4: stream = QDataStream(self.buffer) msg = Message.fromInt(stream.readInt32()) if msg == None: return args = [] bytesRead = 4 for aType in msg.argTypes: if aType == str: if self.buffer.bytesAvailable() < 4: return length = stream.readInt32() if self.buffer.bytesAvailable() < length: return args.append(stream.readRawData(length)) bytesRead += 4 + length elif aType == int: if self.buffer.bytesAvailable() < 4: return args.append(stream.readInt32()) bytesRead += 4 elif aType == long: if self.buffer.bytesAvailable() < 8: return args.append(stream.readInt64()) bytesRead += 8 return (msg, args, bytesRead) def sendMessage(self, msg, args, id = None): """Sends a message. msg -- The message type. args -- List of message arguments. id -- An optional socket descriptor. If specified, then the message will only be sent if this connection's socket descriptor matches id.""" if id: if self.socketDescriptor() != id: return msg = Message.fromInt(msg) if not msg.validateArgs(args): log.warning("Message %d and args %s have invalid types. Message not sent.", msg, args) return if self.client: log.debug("Sending %s %s", msg, args) elif self.player and self.player.name: log.debug("Sending %s %s to %s", msg, args, self.player) else: log.debug("Sending %s %s to %s", msg, args, self.peerAddress().toString()) data = QByteArray() stream = QDataStream(data, self.WriteOnly) stream.writeInt32(int(msg)) for arg in args: if type(arg) == str: stream.writeInt32(len(arg)) stream.writeRawData(arg) elif type(arg) == int: stream.writeInt32(arg) elif type(arg) == long: stream.writeInt64(arg) self.write(data) self.messageSent.emit(msg, args)
def to_jpeg(self, quality=None): if quality is None: quality = defaults.JPEG_QUALITY buf = QBuffer() self.img.save(buf, 'jpeg', quality) return bytes(buf.data())
def renderer(self): if 'QGIS_AUTH_DB_DIR_PATH' not in os.environ: os.environ['QGIS_AUTH_DB_DIR_PATH'] = '/tmp' qgis = None while True: options, result = self.queue.get() # Don't start QGIS until first request if qgis is None: qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setDefaultSvgPaths(qgis.svgPaths() + self.settings.get('svgpaths')) qgis.setMaxThreads(1) qgis.initQgis() try: if isinstance(options, LegendOptions): style, = options layer = self._qgs_memory_layer(style) layer.setName(style.parent.display_name) QgsMapLayerRegistry.instance().addMapLayer(layer) root = QgsLayerTreeGroup() root.addLayer(layer) # 'Cannot create a QPixmap when no GUI is being used' # warning occurs here model = QgsLayerTreeModel(root) settings = QgsLegendSettings() settings.setTitle('') settings.setBoxSpace(1) settings.setSymbolSize(QSizeF(5, 3)) settings.setDpi(96) renderer = QgsLegendRenderer(model, settings) # Dots per mm dpmm = settings.dpi() / 25.4 min_size = renderer.minimumSize() size = QSize(dpmm * min_size.width(), dpmm * min_size.height()) img = QImage(size, QImage.Format_ARGB32) img.fill(QColor(0, 0, 0, 0)) painter = QPainter() painter.begin(img) painter.scale(dpmm, dpmm) renderer.drawLegend(painter) painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) result.put(buf) else: path = features = None if isinstance(options, VectorRenderOptions): style, features, render_size, \ extended, target_box = options layer = self._qgs_memory_layer(style, features=features) elif isinstance(options, RasterRenderOptions): style, path, render_size, \ extended, target_box = options layer = QgsRasterLayer(path) layer.loadNamedStyle( self.env.file_storage.filename(style.qml_fileobj)) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(layer.crs()) settings.setMapUnits(layer.crs().mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Create QImage by hand to be able to use # QgsMapRendererCustomPainterJob. Others will not # allow to workaround a bug with overlay rendering. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # These cludges are needed for rendering # on transparent background, otherwise it's a mess. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI should be equal to settings, otherwise an error. # In QImage the resolution is set in dots per meter # for each axis. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() img = self._qimage_to_pil(img) # Clip needed part result.put(img.crop(target_box)) # Cleanup if path is not None: gdal.Unlink(path) except Exception as exc: self.logger.error(exc.message) result.put(exc) qgis.exitQgis()
def do_GET(self): try: self.path = re.sub('[^.a-zA-Z0-9]', "", str(self.path)) if self.path == "" or self.path == None or self.path[:1] == ".": self.send_error(403, 'Forbidden') if self.path.endswith(".html"): directory = os.path.dirname(os.path.abspath(__file__)) data = open(os.path.join(directory, self.path), "rb").read() self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(data) elif self.path.endswith(".mjpeg"): self.thread = thread = OSCThread(self.server.args) thread.daemon = True thread.start() actor_names = ["merle", "uwe", "bjoern"] num_data = 100 colors = ["r", "g", "b"] qtapp = QtGui.QApplication([]) plotter = EkgPlot(actor_names, num_data, colors) self.send_response(200) self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--2342") self.end_headers() event_loop = QtCore.QEventLoop() last_frame = time.time() - 1.0 frame_rate = 13.0 frame_length = 1. / frame_rate plotter.new_round() while 1: event_loop.processEvents() qtapp.sendPostedEvents(None, 0) while 1: try: osc_address, args = queue.get_nowait() plotter.update(osc_address, args[0]) except Queue.Empty: break now = time.time() delta = now - last_frame if delta > frame_length: plotter.update_missing_actors() plotter.render() exporter = pg.exporters.ImageExporter.ImageExporter( plotter.plot.plotItem) exporter.parameters()['width'] = 768 img = exporter.export(toBytes=True) buffer = QBuffer() buffer.open(QIODevice.WriteOnly) img.save(buffer, "JPG") JpegData = buffer.data() self.wfile.write( "--2342\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData)) last_frame = now plotter.new_round() #JpegData = None #buffer = None #img = None #exporter = None time.sleep(0.01) except (KeyboardInterrupt, SystemError), e: raise e
def do_GET(self): self.thread = thread = OSCThread() thread.daemon = True thread.start() actors = list() is_item1 = True is_item2 = True is_item3 = True def setPositions(): for ix, item in enumerate(actors): item.setPos(0, ix * 6) def scale_data(data, ix, max_items): scale = 254 / max_items * ix return [value / max_items + scale for value in data] try: self.path = re.sub('[^.a-zA-Z0-9]', "", str(self.path)) if self.path == "" or self.path == None or self.path[:1] == ".": return if self.path.endswith(".html"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(f.read()) f.close() elif self.path.endswith(".mjpeg"): data_points = 1000 self.send_response(200) plot_data1 = data = deque([0] * data_points) plot_data2 = data = deque([0] * data_points) plot_data3 = data = deque([0] * data_points) plt = PlotWidget(title="<h1>EKG</h1>", name="Merle") plt.hide() plotItem1 = pg.PlotCurveItem(pen=pg.mkPen('r', width=2), name="bjoern") plotItem2 = pg.PlotCurveItem(pen=pg.mkPen('g', width=2), name="merle") plotItem3 = pg.PlotCurveItem(pen=pg.mkPen('b', width=2), name="uwe") print type(plotItem1) pen = pg.mkPen(254, 254, 254) plotItem1.setShadowPen(pen=pen, width=6, cosmetic=True) plotItem2.setShadowPen(pen=pen, width=6, cosmetic=True) plotItem3.setShadowPen(pen=pen, width=6, cosmetic=True) actors.append(plotItem1) actors.append(plotItem2) actors.append(plotItem3) plotItem1.setPos(0, 0 * 6) plotItem2.setPos(0, 1 * 6) plotItem3.setPos(0, 2 * 6) plt.addItem(plotItem1) plt.addItem(plotItem2) plt.addItem(plotItem3) plt.setLabel('left', "<h2>Amplitude</h2>") plt.setLabel('bottom', "<h2>Time</h2>") plt.showGrid(True, True) ba = plt.getAxis("bottom") bl = plt.getAxis("left") ba.setTicks([]) bl.setTicks([]) plt.setYRange(0, 254) self.wfile.write( "Content-Type: multipart/x-mixed-replace; boundary=--aaboundary" ) self.wfile.write("\r\n\r\n") plt.resize(1280, 720) while 1: while 1: try: osc_address, args = queue.get_nowait() except Queue.Empty: break value = args[0] if osc_address == "/bjoern/ekg": plot_data1.append(value) plot_data1.popleft() try: plotItem1.setData(y=np.array( scale_data(plot_data1, actors.index(plotItem1), len(actors))), clear=True) except ValueError: pass elif osc_address == "/merle/ekg": plot_data2.append(value) plot_data2.popleft() try: plotItem2.setData(y=np.array( scale_data(plot_data2, actors.index(plotItem2), len(actors))), clear=True) except ValueError: pass elif osc_address == "/uwe/ekg": plot_data3.append(value) plot_data3.popleft() try: plotItem3.setData(y=np.array( scale_data(plot_data3, actors.index(plotItem3), len(actors))), clear=True) except ValueError: pass elif osc_address == "/plot/uwe": if value == 1 and is_item3 == False: print "uwe on" plt.addItem(plotItem3) is_item3 = True actors.append(plotItem3) setPositions() elif value == 0 and is_item3 == True: print "uwe off" plt.removeItem(plotItem3) is_item3 = False actors.remove(plotItem3) setPositions() elif osc_address == "/plot/merle": if value == 1 and is_item2 == False: print "merle on" plt.addItem(plotItem2) is_item2 = True actors.append(plotItem2) setPositions() elif value == 0 and is_item2 == True: print "merle off" plt.removeItem(plotItem2) is_item2 = False actors.remove(plotItem2) setPositions() elif osc_address == "/plot/bjoern": if value == 1 and is_item1 == False: print "bjoern on" plt.addItem(plotItem1) is_item1 = True actors.append(plotItem1) setPositions() elif value == 0 and is_item1 == True: print "bjoern off" plt.removeItem(plotItem1) is_item1 = False actors.remove(plotItem1) setPositions() exporter = pg.exporters.ImageExporter.ImageExporter( plt.plotItem) img = exporter.export("tmpfile", True) buffer = QBuffer() buffer.open(QIODevice.WriteOnly) img.save(buffer, "JPG", 100) JpegData = buffer.data() del buffer self.wfile.write( "--aaboundary\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData)) elif self.path.endswith(".jpeg"): f = open(curdir + sep + self.path) self.send_response(200) self.send_header('Content-type', 'image/jpeg') self.end_headers() self.wfile.write(f.read()) f.close() return except (KeyboardInterrupt, SystemError): thread.running = False thread.join() except IOError: self.send_error(404, 'File Not Found: %s' % self.path)
def OCRperformOCRDigit(x,y,w,h): rvalue = '' img = QPixmap.grabWindow(QApplication.desktop().winId(),x,y,w,h) img.save('test.png', 'png') buffer = QBuffer() buffer.open(QIODevice.ReadWrite) img.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) im = Image.open(strio) #im = Image.open('/home/liutauras/Documents/Python/test.png') pixdata = im.load(); for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 550: pixdata[x, y] = (255, 255, 255) else: pixdata[x, y] = (0, 0, 0) #Add extra space on each side for y in xrange(im.size[1]): pixdata[0,y] = (255, 255, 255) pixdata[1,y] = (255, 255, 255) pixdata[im.size[0]-1,y] = (255, 255, 255) pixdata[im.size[0]-2,y] = (255, 255, 255) for x in xrange(im.size[0]): pixdata[x,0] = (255, 255, 255) pixdata[x,1] = (255, 255, 255) pixdata[x,im.size[1]-1] = (255, 255, 255) pixdata[x,im.size[1]-2] = (255, 255, 255) nx, ny = im.size im = im.resize((nx*5, ny*5), Image.ANTIALIAS) enh = ImageEnhance.Contrast(im) pixdata = im.load() for y in xrange(im.size[1]): for x in xrange(im.size[0]): total = pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if total < 500: pixdata[x, y] = (0, 0, 0) else: pixdata[x, y] = (255, 255, 255) im = im.resize((int(nx*5), int(ny*5)), Image.BILINEAR) #rvalue = OCR_to_string(im,True) pixdata = im.load() #Correct 4 not to overlap lastTot2 = 0 lastTot = 0; for x in xrange(im.size[0]): total = 0 for y in xrange(26,im.size[1]): total = total + sum(pixdata[x, y]) if(total == 20655 and lastTot == 20655 and lastTot2 == 9180): x = x - 1 for xT in range(x,3+x): for y in xrange(25,43): pixdata[xT,y] = (270,270,270) for xT in range(x,6+x): for y in xrange(35,40): pixdata[xT,y] = (270,270,270) lastTot2 = lastTot lastTot = total #Spit by Character totalSumLast = 0 startX = 0 for x in xrange(im.size[0]): #Start of digits flag totalSum = 0 for y in xrange(im.size[1]): totalSum = totalSum + pixdata[x, y][0] + pixdata[x, y][1] + pixdata[x, y][2] if(totalSum < totalSumLast and totalSumLast == 45900): startX = x for y in xrange(im.size[1]): pixdata[x, y] = (0, 0, 0) elif(totalSum > totalSumLast and totalSum == 45900 and startX != 0): #Detect start on y axis startY = 0 for y1 in xrange(im.size[1]): innerSum = 0 divTot = 0 for x1 in xrange(startX,x): innerSum = innerSum + sum(pixdata[x1, y1]) divTot = divTot + 1 innerSum = innerSum/divTot if(startY == 0 and innerSum < 630): startY = y1 elif(startY != 0 and innerSum > 630): for x1 in xrange(startX,x): pixdata[x1, startY] = (0, 200, 0) pixdata[x1, y1] = (0, 0, 200) #Total area sum totalAreaSum = 0 for x1 in xrange(startX,x): for y2 in xrange(startY,y1): totalAreaSum = totalAreaSum + sum(pixdata[x1, y2]) #Decoding digit if(totalAreaSum == 190060): rvalue = rvalue + '1' elif(totalAreaSum == 8285): rvalue = rvalue + '.' elif(totalAreaSum == 231605 or totalAreaSum == 237725): rvalue = rvalue + '4' elif(totalAreaSum == 283625): rvalue = rvalue + '2' elif(totalAreaSum == 245375): rvalue = rvalue + '5' elif(totalAreaSum == 321875): rvalue = rvalue + '7' elif(totalAreaSum == 251495): rvalue = rvalue + '9' elif(totalAreaSum == 228545): rvalue = rvalue + '0' elif(totalAreaSum == 275975): rvalue = rvalue + '3' elif(totalAreaSum == 262970): rvalue = rvalue + '6' elif(totalAreaSum == 217070): rvalue = rvalue + '8' elif(totalAreaSum == 236195): rvalue = rvalue + '0' elif(totalAreaSum == 223190): rvalue = rvalue + '8' elif(totalAreaSum == 270620): rvalue = rvalue + '6' else: print '-------------------------' subprocess.call(['/usr/bin/canberra-gtk-play','--id','bell']) rvalue = rvalue + '' filename = 'errorB'+rvalue+'|'+str(totalAreaSum)+'|'+str(random.randint(1,1000))+'.png' print '--------E---------------' img.save(filename, 'png') print filename,totalAreaSum print '-------------------------' #print totalAreaSum startY = 0 startX = 0 for y in xrange(im.size[1]): pixdata[x, y] = (200, 0, 0) totalSumLast = totalSum #rvalue = '0'+rvalue rvalue = rvalue.replace('\n','').replace(' ','') if(len(rvalue) > 0): im.save("a.png") rvalue = rvalue.replace(',','').replace(' ','').replace('.','') rvalue = int(rvalue) else: rvalue = 0 return rvalue
def renderer(self): qgis = QgsApplication([], False) qgis.setPrefixPath(self.settings.get('path'), True) qgis.setMaxThreads(1) qgis.initQgis() while True: try: fndata, srs, render_size, extended, \ target_box, result = self.queue.get() layer = QgsVectorLayer(fndata, 'layer', 'ogr') crs = QgsCoordinateReferenceSystem(srs.id) layer.setCrs(crs) settings = QgsMapSettings() settings.setLayers([layer.id()]) settings.setFlag(QgsMapSettings.DrawLabeling) settings.setFlag(QgsMapSettings.Antialiasing) settings.setCrsTransformEnabled(True) settings.setDestinationCrs(crs) settings.setMapUnits(crs.mapUnits()) settings.setOutputSize(QSize(*render_size)) settings.setExtent(QgsRectangle(*extended)) settings.setOutputImageFormat(QImage.Format_ARGB32) bgcolor = QColor.fromRgba(qRgba(255, 255, 255, 0)) settings.setBackgroundColor(bgcolor) settings.setOutputDpi(96) QgsMapLayerRegistry.instance().addMapLayer(layer) settings.setLayers([layer.id()]) # Создаем QImage руками чтобы можно было использовать # QgsMapRendererCustomPainterJob. Остальные не позволяют # обойти баг с рисованием поверх старого. img = QImage(settings.outputSize(), QImage.Format_ARGB32) # Эти костыли нужны для того, чтобы корректно рисовались # слои на прозрачном фоне, без этого получается каша. img.fill(QColor.fromRgba(qRgba(255, 255, 255, 255))) img.fill(QColor.fromRgba(qRgba(255, 255, 255, 0))) # DPI должно быть таким же как в settings, иначе ошибка. В QImage # разрешение указывается в точках на метр по каждой оси. dpm = settings.outputDpi() / 25.4 * 1000 img.setDotsPerMeterX(dpm) img.setDotsPerMeterY(dpm) painter = QPainter(img) job = QgsMapRendererCustomPainterJob(settings, painter) job.renderSynchronously() painter.end() QgsMapLayerRegistry.instance().removeAllMapLayers() # Преобразование QImage в PIL ba = QByteArray() bf = QBuffer(ba) bf.open(QIODevice.WriteOnly) img.save(bf, 'PNG') bf.close() buf = StringIO() buf.write(bf.data()) buf.seek(0) img = PIL.Image.open(buf) # Вырезаем нужный нам кусок изображения result.put(img.crop(target_box)) except Exception as e: self.logger.error(e.message) qgis.exitQgis()