python存储16bit和32bit图像的实例
笔记:python中存储16bit和32bit图像的方法。
说明:主要是利用scipy库和pillow库,比较其中的不同。
'''
测试16bit和32bit图像的python存储方法
'''
import numpy as np
import scipy.misc
from PIL import Image
# 用已有的8bit和16bit图作存储测试
path16 = 'D:\Py_exercise\lena16.tif'
path8 = 'D:\Py_exercise\lena8.tif'
tif16 = scipy.misc.imread(path16) #
tif8 = scipy.misc.imread(path8) #
print(np.shape(tif16),type(tif16[0,0]))
print(np.shape(tif8),type(tif8[0,0]))
print()
save16 = 'D:\Py_exercise\lena16_save.tif'
save8 = 'D:\Py_exercise\lena8_save.tif'
scipy.misc.imsave(save16, tif16) #--> 8bit
scipy.misc.imsave(save8, tif8) #--> 8bit
# Create a mat which is 64 bit float
nrows = 512
ncols = 512
np.random.seed(12345)
y = np.random.randn(nrows, ncols)*65535 #
print(type(y[0,0]))
print()
# Convert y to 16 bit unsigned integers
z16 = (y.astype(np.uint16)) #
print(type(z16[0,0]))
print()
# 用产生的随机矩阵作存储测试
save16 = 'D:\Py_exercise\lena16_save1.tif'
scipy.misc.imsave(save16, z16) #--> 8bit
im = Image.frombytes('I;16', (ncols,nrows), y.tostring())
im.save('D:\Py_exercise\lena16_save21.tif') #--> 16bit
im = Image.fromarray(y)
im.save('D:\Py_exercise\lena16_save22.tif') #--> 32bit
im = Image.fromarray(z16)
im.save('D:\Py_exercise\lena16_save23.tif') #--> 16bit
# 归一化后的np.float64仍然存成了uint8
zNorm = (z16-np.min(z16))/(np.max(z16)-np.min(z16)) #
print(type(zNorm[0,0]))
save16 = 'D:\Py_exercise\lena16_save11.tif'
scipy.misc.imsave(save16, zNorm) #--> 8bit
# 归一化后的np.float64直接转8bit或16bit都会超出阈值,要*255或*65535
# 如果没有astype的位数设置,会直接存成32bit
zImg = (zNorm*65535).astype(np.uint16)
im = Image.fromarray(zImg)
im.save('D:\Py_exercise\lena16_save31.tif') #--> 16bit
im = Image.fromarray(zNorm)
im.save('D:\Py_exercise\lena16_save32.tif') #--> 32bit(0~1)
以上这篇python存储16bit和32bit图像的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持码农之家。
Python的bit_length函数来二进制的位数方法
自Python3.1中,整数bit_length方法允许查询二进制的位数或长度。
常规做法:
>>> bin(256)
'0b100000000'
>>> len(bin(256)) - 2
9
>>>
使用函数:
>>> bin(256), (256).bit_length()
('0b100000000', 9)
>>> X = 99
>>> bin(X), X.bit_length()
('0b1100011', 7)
>>>
以上这篇Python的bit_length函数来二进制的位数方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持码农之家。
Python队列RabbitMQ 使用方法实例记录
本文实例讲述了Python队列RabbitMQ 使用方法。分享给大家供大家参考,具体如下:
目前的exchange的路由策略是:每个需要队列的服务独享一个队列(queue),消费者(consumer)采用ACK自动应答模式处理队列消息。
如果需要新增一个队列服务,需要做如下开发步骤:
1.创建队列,发送消息
$routingkey = 'key';
//设置你的连接
$conn_args = array('host' => 'localhost', 'port' => '5672', 'login' => 'guest', 'password' => 'guest');
$conn = new AMQPConnection($conn_args);
if ($conn->connect()) {
echo "Established a connection to the broker \n";
} else {
echo "Cannot connect to the broker \n ";
}
//你的消息
$message = json_encode(array('Hello World3!', 'php3', 'c++3:'));
//创建channel
$channel = new AMQPChannel($conn);
//创建exchange
$ex = new AMQPExchange($channel);
$ex->setName('exchange2'); //创建名字
$ex->setType(AMQP_EX_TYPE_DIRECT);
$ex->setFlags(AMQP_DURABLE);
echo "exchange2 status:" . $ex->declareExchange();
echo "\n";
for ($i = 0; $i < 100; $i++) {
if ($routingkey == 'key2') {
$routingkey = 'key';
} else {
$routingkey = 'key2';
}
$ex->publish($message, $routingkey);
}
这样就产生了50条消息,但是没有消费者,所以没有被消费
2.创建消费者,消费信息
set_time_limit(0);
$e_name = 'exchange2'; //交换机名
$q_name = 'queue2'; //队列名
$k_route = 'key2'; //路由key
//连接RabbitMQ
$conn_args = array('host' => '127.0.0.1', 'port' => '5672', 'login' => 'guest', 'password' => 'guest', 'vhost' => '/');
$conn = new AMQPConnection($conn_args);
$conn->connect();
$channel = new AMQPChannel($conn);
//创建交换机
$ex = new AMQPExchange($channel);
$ex->setName($e_name);
$ex->setType(AMQP_EX_TYPE_DIRECT); //direct类型
$ex->setFlags(AMQP_DURABLE); //持久化
echo "Exchange Status:" . $ex->declareExchange() . "\n";
//创建队列
$q = new AMQPQueue($channel);
$q->setName($q_name);
$q->setFlags(AMQP_DURABLE); //持久化
//绑定交换机与队列,并指定路由键
echo 'Queue Bind: ' . $q->bind($e_name, $k_route) . "\n"; //阻塞模式接收消息
echo "Message:\n";
$q->consume('processMessage', AMQP_AUTOACK); //自动ACK应答
$conn->disconnect();
/** * 消费回调函数 * 处理消息 */
function processMessage($envelope, $queue) {
var_dump($envelope->getRoutingKey());
$msg = $envelope->getBody();
echo $msg . "\n"; //处理消息
}
运行之后
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
Python操作rabbitMQ的示例代码
引入
RabbitMQ 是一个由 Erlang 语言开发的 AMQP 的开源实现。
rabbitMQ是一款基于AMQP协议的消息中间件,它能够在应用之间提供可靠的消息传输。在易用性,扩展性,高可用性上表现优秀。使用消息中间件利于应用之间的解耦,生产者(客户端)无需知道消费者(服务端)的存在。而且两端可以使用不同的语言编写,大大提供了灵活性。
中文文档
安装
# 安装配置epel源
rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
# 安装erlang
yum -y install erlang
# 安装RabbitMQ
yum -y install rabbitmq-server
# 启动/停止
service rabbitmq-server start/stop
rabbitMQ工作模型
简单模式
生产者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
消费者
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume( callback,
queue='hello',
no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
相关参数
1,no-ack = False
如果消费者遇到情况(its channel is closed, connection is closed, or TCP connection is lost)挂掉了,那么,RabbitMQ会重新将该任务添加到队列中。
回调函数中的 ch.basic_ack(delivery_tag=method.delivery_tag)
basic_comsume中的no_ack=False
接收消息端应该这么写:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='10.211.55.4'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
import time
time.sleep(10)
print 'ok'
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_consume(callback,
queue='hello',
no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
2,durable :消息不丢失
生产者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel()
# make message persistent
channel.queue_declare(queue='hello', durable=True)
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!',
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
print(" [x] Sent 'Hello World!'")
connection.close()
3,消息获取顺序
默认消息队列里的数据是按照顺序被消费者拿走,例如:消费者1 去队列中获取 奇数 序列的任务,消费者1去队列中获取 偶数 序列的任务。
channel.basic_qos(prefetch_count=1) 表示谁来谁取,不再按照奇偶数排列
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='10.211.55.4'))
channel = connection.channel()
# make message persistent
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
import time
time.sleep(10)
print 'ok'
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
queue='hello',
no_ack=False)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
exchange模型
1,发布订阅
发布订阅和简单的消息队列区别在于,发布订阅会将消息发送给所有的订阅者,而消息队列中的数据被消费一次便消失。所以,RabbitMQ实现发布和订阅时,会为每一个订阅者创建一个队列,而发布者发布消息时,会将消息放置在所有相关队列中。
exchange type = fanout
生产者
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
type='fanout')
message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs',
routing_key='',
body=message)
print(" [x] Sent %r" % message)
connection.close()
消费者
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs',
type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs',
queue=queue_name)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r" % body)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
2,关键字发送
之前事例,发送消息时明确指定某个队列并向其中发送消息,RabbitMQ还支持根据关键字发送,即:队列绑定关键字,发送者将数据根据关键字发送到消息exchange,exchange根据 关键字 判定应该将数据发送至指定队列。
exchange type = direct
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='direct_logs',
type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
severities = sys.argv[1:]
if not severities:
sys.stderr.write("Usage: %s [info] [warning] [error]\n" % sys.argv[0])
sys.exit(1)
for severity in severities:
channel.queue_bind(exchange='direct_logs',
queue=queue_name,
routing_key=severity)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
3,模糊匹配
exchange type = topic
发送者路由值 队列中
old.boy.python old.* -- 不匹配
old.boy.python old.# -- 匹配
在topic类型下,可以让队列绑定几个模糊的关键字,之后发送者将数据发送到exchange,exchange将传入”路由值“和 ”关键字“进行匹配,匹配成功,则将数据发送到指定队列。
# 表示可以匹配 0 个 或 多个 单词
* 表示只能匹配 一个 单词
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='topic_logs',
type='topic')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
binding_keys = sys.argv[1:]
if not binding_keys:
sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
sys.exit(1)
for binding_key in binding_keys:
channel.queue_bind(exchange='topic_logs',
queue=queue_name,
routing_key=binding_key)
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r:%r" % (method.routing_key, body))
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
基于rabbitMQ的RPC
Callback queue 回调队列
一个客户端向服务器发送请求,服务器端处理请求后,将其处理结果保存在一个存储体中。而客户端为了获得处理结果,那么客户在向服务器发送请求时,同时发送一个回调队列地址 reply_to 。
Correlation id 关联标识
一个客户端可能会发送多个请求给服务器,当服务器处理完后,客户端无法辨别在回调队列中的响应具体和那个请求时对应的。为了处理这种情况,客户端在发送每个请求时,同时会附带一个独有 correlation_id 属性,这样客户端在回调队列中根据 correlation_id 字段的值就可以分辨此响应属于哪个请求。
客户端发送请求:
某个应用将请求信息交给客户端,然后客户端发送RPC请求,在发送RPC请求到RPC请求队列时,客户端至少发送带有reply_to以及correlation_id两个属性的信息
服务端工作流:
等待接受客户端发来RPC请求,当请求出现的时候,服务器从RPC请求队列中取出请求,然后处理后,将响应发送到reply_to指定的回调队列中
客户端接受处理结果:
客户端等待回调队列中出现响应,当响应出现时,它会根据响应中correlation_id字段的值,将其返回给对应的应用
服务者
import pika
# 建立连接,服务器地址为localhost,可指定ip地址
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
# 建立会话
channel = connection.channel()
# 声明RPC请求队列
channel.queue_declare(queue='rpc_queue')
# 数据处理方法
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
# 对RPC请求队列中的请求进行处理
def on_request(ch, method, props, body):
n = int(body)
print(" [.] fib(%s)" % n)
# 调用数据处理方法
response = fib(n)
# 将处理结果(响应)发送到回调队列
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id = \
props.correlation_id),
body=str(response))
ch.basic_ack(delivery_tag = method.delivery_tag)
# 负载均衡,同一时刻发送给该服务器的请求不超过一个
channel.basic_qos(prefetch_count=1)
channel.basic_consume(on_request, queue='rpc_queue')
print(" [x] Awaiting RPC requests")
channel.start_consuming()
客户端
import pika
import uuid
class FibonacciRpcClient(object):
def __init__(self):
"""
客户端启动时,创建回调队列,会开启会话用于发送RPC请求以及接受响应
"""
# 建立连接,指定服务器的ip地址
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
# 建立一个会话,每个channel代表一个会话任务
self.channel = self.connection.channel()
# 声明回调队列,再次声明的原因是,服务器和客户端可能先后开启,该声明是幂等的,多次声明,但只生效一次
result = self.channel.queue_declare(exclusive=True)
# 将次队列指定为当前客户端的回调队列
self.callback_queue = result.method.queue
# 客户端订阅回调队列,当回调队列中有响应时,调用`on_response`方法对响应进行处理;
self.channel.basic_consume(self.on_response, no_ack=True,
queue=self.callback_queue)
# 对回调队列中的响应进行处理的函数
def on_response(self, ch, method, props, body):
if self.corr_id == props.correlation_id:
self.response = body
# 发出RPC请求
def call(self, n):
# 初始化 response
self.response = None
#生成correlation_id
self.corr_id = str(uuid.uuid4())
# 发送RPC请求内容到RPC请求队列`rpc_queue`,同时发送的还有`reply_to`和`correlation_id`
self.channel.basic_publish(exchange='',
routing_key='rpc_queue',
properties=pika.BasicProperties(
reply_to = self.callback_queue,
correlation_id = self.corr_id,
),
body=str(n))
while self.response is None:
self.connection.process_data_events()
return int(self.response)
# 建立客户端
fibonacci_rpc = FibonacciRpcClient()
# 发送RPC请求
print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" % response)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。
win10 64bit下python NLTK安装教程
由于最近需要做项目,需要进行分词等,查了资料之后,发现python NLTK很强大,于是就想试试看。在网上找了很多安装资料,都不太完整,下载的时候也总是会出现一点小意外,最后终于也安装成功了,所以分享下经验。
初学者,请高手指出不合理的地方。
我的工作站环境是Win10 64 + Python 2.7.12 64 bit。
按照NLTK上安装主页上的指引如下:
Source installation (for 32-bit or 64-bit Windows)
1.Install Python: http://www.python.org/download/releases/2.7.3/
2.Install Numpy (optional): http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
3.Install Setuptools: http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11.win32-py2.7.exe
4.Install Pip: Start>Run... c:\Python27\Scripts\easy_install pip
5.Install PyYAML and NLTK: Start>Run... c:\Python27\Scripts\pip install pyyaml nltk
6.Test installation: Start>All Programs>Python27>IDLE, then type import nltk
前3步的安装都比较简单,如果为了更好的编辑,也可以安装一下编辑软件,如PyCharm,Sublime text2/3等等。在安装的时候要注意安装路径,最好不要出现中文。
我在安装第4步的时候出现了一点小问题,执行命令后报错:Python version 2.7 required, which was not found in the registry,于是我又到网上查了资料,解决方法是:
1)自己新建一个register.py文件,在文件中复制黏贴以下内容,然后保存到自己的路径,我是直接放到pyhon的安装文件夹中;
#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# written by Joakim Loew for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm
#
# modified by Valentine Gogichashvili as described in http://www.mail-archive.com/distutils-sig@python.org/msg10512.html
import sys
from _winreg import *
# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix
regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
installpath, installpath, installpath
)
def RegisterPy():
try:
reg = OpenKey(HKEY_CURRENT_USER, regpath)
except EnvironmentError as e:
try:
reg = CreateKey(HKEY_CURRENT_USER, regpath)
SetValue(reg, installkey, REG_SZ, installpath)
SetValue(reg, pythonkey, REG_SZ, pythonpath)
CloseKey(reg)
except:
print "*** Unable to register!"
return
print "--- Python", version, "is now registered!"
return
if (QueryValue(reg, installkey) == installpath and
QueryValue(reg, pythonkey) == pythonpath):
CloseKey(reg)
print "=== Python", version, "is already registered!"
return
CloseKey(reg)
print "*** Unable to register!"
print "*** You probably have another Python installation!"
if __name__ == "__main__":
RegisterPy()
2)Ctrl+R打开cmd,然后进入python的安装目录(如果有配置环境变量的话,就不用这么麻烦了,可以直接命令操作),输入:python register.py(这个是刚才存错register.py的路径,如D:\register.py)。出现Python 2.7 is already registered!则表示配置成功。
3)接着,进入Scripts目录,输入:easy_install pip,提示安装成功。
第5步是安装PyYAML和NLTK。直接在刚才的目录中输入:pip install pyyaml nltk,这时会提示安装是否成功,若安装成功可以接着下一步。
此时,就可以到IDLE中进行下载NLTK的数据包:
稍等一会,就出现了如下的页面,弹出如下窗口,即完成了。我是选择下载了所有的data,你可以根据自己的需要进行下载。要等很久才会完成这个过程,慢慢来,最后就可以测试啦。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。
以上就是本次给大家分享的关于java的全部知识点内容总结,大家还可以在下方相关文章里找到相关文章进一步学习,感谢大家的阅读和支持。