2016-06-26 21 views
0

我需要與RabbitMQ的,我發現的唯一途徑發送圖像是:如何將磁盤上的簡單圖像轉換爲OpenCV mat文件?

f = open("asd.jpg","rb") 
img = f.read() 
f.close() 

比我能發送img

我想處理髮送的圖像,我收到它,所以我如何將它轉換爲OpenCV mat文件?

這裏是我收到的文件:

def callback(ch, method, properties, body): 
    print "Recieved" 
    cv2.imshow('Message', body) 
    cv2.waitKey(0) 

Send.py

import pika 
import cv2 

img = cv2.imread('asd.jpg') 

#Establish connection 
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) 
channel = connection.channel() 

channel.exchange_declare(exchange='image_exch', type='fanout') 

channel.basic_publish(exchange='image_exch', routing_key='', body=img) 

print "[*] Sent" 

connection.close() 

Receive.py

import pika 
import cv2 

#Establish connection 
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) 
channel = connection.channel() 

channel.exchange_declare(exchange='image_exch', type='fanout') 
result = channel.queue_declare(exclusive=True) 
queue_name = result.method.queue 

channel.queue_bind(exchange='image_exch', queue=queue_name) 

def callback(ch, method, properties, body): 
    print "Recieved" 
    cv2.imshow('Message', body) 
    cv2.waitKey(0) 

channel.basic_consume(callback, queue=queue_name, no_ack=True) 
print(' [*] Waiting for messages. To exit press CTRL+C') 
channel.start_consuming() 
+0

爲什麼你不只是使用opencv讀取圖像?它將被讀作一個numpy數組。 –

+0

因此,首先我必須保存它,並用openCV再次讀取它?或者我不明白。 – Gabe

+0

檢查我的答案。 –

回答

0

所以經過幾次嘗試我設法解決我的問題。

這是我做的:

#Read the image as binary 
f = open("picture.jpg","rb") 
rawImg= f.read() 
f.close() 

#Convert the raw image to a numpy array for further processing 
npImage = np.fromstring(rawImg, dtype='uint8') 
#Convert the numpy array to an OpenCV image type 
img = cv2.imdecode(npImage, cv2.IMREAD_UNCHANGED) 
cv2.imshow('Recieved message', img) 
cv2.waitKey(0) 

而這個完美支援的RabbitMQ和OpenCV。只需將圖像作爲二進制文件與發送者腳本一起讀取即可發送。收到郵件後,只需將其轉換並完成即可。

相關問題