本文整理汇总了Python中PyQt4.QtCore.QBuffer.close方法的典型用法代码示例。如果您正苦于以下问题:Python QBuffer.close方法的具体用法?Python QBuffer.close怎么用?Python QBuffer.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt4.QtCore.QBuffer
的用法示例。
在下文中一共展示了QBuffer.close方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: newfunc
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
def newfunc():
ba = QByteArray(data) # keep reference to avoid GC
f = QBuffer(ba)
f.open(mode)
try:
func(f)
finally:
f.close()
示例2: QIm2PIL
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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
示例3: OCRperformOCRName
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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
示例4: capture_image
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
def capture_image(session, selector=None, outformat="jpg"):
""" capture page as image """
# do capture now
cap = None
if selector is not None:
cap = session.capture(selector=selector)
else:
cap = session.capture()
# create a buffered image
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
cap.save(buffer, 'JPG' if outformat.upper() in ('JPG', 'JPEG') else 'PNG')
buffer.close()
return buffer, 'image/' + 'jpeg' if outformat.upper() in ('JPG','JPEG') else 'png'
示例5: render
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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()
示例6: getLegendGraphic
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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()
示例7: Connection
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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:
#.........这里部分代码省略.........
示例8: Window
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
format = QAudioFormat()
format.setChannels(1)
format.setFrequency(22050)
format.setSampleSize(16)
format.setCodec("audio/pcm")
format.setByteOrder(QAudioFormat.LittleEndian)
format.setSampleType(QAudioFormat.SignedInt)
self.output = QAudioOutput(format, self)
self.frequency = 440
self.volume = 0
self.buffer = QBuffer()
self.data = QByteArray()
self.deviceLineEdit = QLineEdit()
self.deviceLineEdit.setReadOnly(True)
self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName())
self.pitchSlider = QSlider(Qt.Horizontal)
self.pitchSlider.setMaximum(100)
self.volumeSlider = QSlider(Qt.Horizontal)
self.volumeSlider.setMaximum(32767)
self.volumeSlider.setPageStep(1024)
self.playButton = QPushButton(self.tr("&Play"))
self.pitchSlider.valueChanged.connect(self.changeFrequency)
self.volumeSlider.valueChanged.connect(self.changeVolume)
self.playButton.clicked.connect(self.play)
formLayout = QFormLayout()
formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)
buttonLayout = QVBoxLayout()
buttonLayout.addWidget(self.playButton)
buttonLayout.addStretch()
horizontalLayout = QHBoxLayout(self)
horizontalLayout.addLayout(formLayout)
horizontalLayout.addLayout(buttonLayout)
def changeFrequency(self, value):
self.frequency = 440 + (value * 2)
def play(self):
if self.output.state() == QAudio.ActiveState:
self.output.stop()
if self.buffer.isOpen():
self.buffer.close()
self.createData()
self.buffer.setData(self.data)
self.buffer.open(QIODevice.ReadOnly)
self.buffer.seek(0)
self.output.start(self.buffer)
def changeVolume(self, value):
self.volume = value
def createData(self):
# Create 2 seconds of data with 22050 samples per second, each sample
# being 16 bits (2 bytes).
self.data.clear()
for i in xrange(2 * 22050):
t = i / 22050.0
value = int(self.volume * sin(2 * pi * self.frequency * t))
self.data.append(struct.pack("<h", value))
示例9: renderer
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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()
示例10: OCRperformOCRDigit
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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
#.........这里部分代码省略.........
示例11: OCRperformOCRPlayerBalance
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
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'
#.........这里部分代码省略.........
示例12: QImage
# 需要导入模块: from PyQt4.QtCore import QBuffer [as 别名]
# 或者: from PyQt4.QtCore.QBuffer import close [as 别名]
img = QImage(iwidth, iheight, QImage.Format_RGB32)
img.setDotsPerMeterX(dpi / 25.4 * 1000)
img.setDotsPerMeterY(dpi / 25.4 * 1000)
img.fill(qRgb(255, 255, 255))
dpi = img.logicalDpiX()
print("Image DPI: %d" % dpi)
render.setOutputSize(QSize(img.width(), img.height()), dpi)
render.setDestinationCrs(crs)
render.setProjectionsEnabled(True)
render.setMapUnits(crs.mapUnits())
render.setExtent(extent)
print("Scale: %f" % render.scale())
painter = QPainter(img)
painter.setRenderHint(QPainter.Antialiasing)
render.render(painter)
painter.end()
ba = QByteArray()
bf = QBuffer(ba)
bf.open(QIODevice.WriteOnly)
img.save(bf, 'PNG')
bf.close()
with open(args.output, 'wb') as fd:
fd.write(ba)