我尝试将图像发送到另一个模块,但我收到连接被拒绝。图像通过 Post 请求从 CameraCapture 发送到 Classify 模块。分类器以拒绝连接响应我。DockerFile 中暴露了 80 端口
来自“iotedge logs CameraCapture”的代码错误:
HTTPConnectionPool(host='classifier', port=80): Max retries exceeded with url: /image (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xf6b447f0>: Failed to establish a new connection: [Errno 111] Connection refused'))
来自 CameraCapture 的 python 脚本:
import time
import sys
import os
import requests
import json
from azure.iot.device import IoTHubModuleClient, Message
# global counters
SENT_IMAGES = 0
# global client
CLIENT = None
# Send a message to IoT Hub
# Route output1 to $upstream in deployment.template.json
def send_to_hub(strMessage):
message = Message(bytearray(strMessage, 'utf8'))
CLIENT.send_message_to_output(message, "output1")
global SENT_IMAGES
SENT_IMAGES += 1
print( "Total images sent: {}".format(SENT_IMAGES) )
# Send an image to the image classifying server
# Return the JSON response from the server with the prediction result
def sendFrameForProcessing(imagePath, imageProcessingEndpoint):
headers = {'Content-Type': 'application/octet-stream'}
with open(imagePath, mode="rb") as test_image:
try:
response = requests.post(imageProcessingEndpoint, headers = headers, data = test_image)
print("Response from classification service: (" + str(response.status_code) + ") " + json.dumps(response.json()) + "\n")
except Exception as e:
print(e)
print("No response from classification service")
print("------------------------------------------------------------------------")
return None
return json.dumps(response.json())
def main(imagePath, imageProcessingEndpoint):
try:
print ( "Simulated camera module for Azure IoT Edge. Press Ctrl-C to exit." )
try:
global CLIENT
CLIENT = IoTHubModuleClient.create_from_edge_environment()
except Exception as iothub_error:
print ( "Unexpected error {} from IoTHub".format(iothub_error) )
return
print ( "The sample is now sending images for processing and will indefinitely.")
while True:
classification = sendFrameForProcessing(imagePath, imageProcessingEndpoint)
if classification:
send_to_hub(classification)
time.sleep(100)
except KeyboardInterrupt:
print ( "IoT Edge module sample stopped" )
if __name__ == '__main__':
try:
# Retrieve the image location and image classifying server endpoint from container environment
IMAGE_PATH = os.getenv('IMAGE_PATH', "")
IMAGE_PROCESSING_ENDPOINT = os.getenv('IMAGE_PROCESSING_ENDPOINT', "http://classifier/image")
except ValueError as error:
print ( error )
sys.exit(1)
if ((IMAGE_PATH and IMAGE_PROCESSING_ENDPOINT) != ""):
main(IMAGE_PATH, IMAGE_PROCESSING_ENDPOINT)
else:
print ( "Error: Image path or image-processing endpoint missing" )
和自定义愿景的代码:
import json
import os
import io
# Imports for the REST API
from flask import Flask, request, jsonify
# Imports for image procesing
from PIL import Image
# Imports for prediction
from predict import initialize, predict_image, predict_url
app = Flask(__name__)
# 4MB Max image size limit
app.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024
# Default route just shows simple text
@app.route('/')
def index():
return 'CustomVision.ai model host harness'
# Like the CustomVision.ai Prediction service /image route handles either
# - octet-stream image file
# - a multipart/form-data with files in the imageData parameter
@app.route('/image', methods=['POST'])
@app.route('/<project>/image', methods=['POST'])
@app.route('/<project>/image/nostore', methods=['POST'])
@app.route('/<project>/classify/iterations/<publishedName>/image', methods=['POST'])
@app.route('/<project>/classify/iterations/<publishedName>/image/nostore', methods=['POST'])
@app.route('/<project>/detect/iterations/<publishedName>/image', methods=['POST'])
@app.route('/<project>/detect/iterations/<publishedName>/image/nostore', methods=['POST'])
def predict_image_handler(project=None, publishedName=None):
try:
imageData = None
if ('imageData' in request.files):
imageData = request.files['imageData']
elif ('imageData' in request.form):
imageData = request.form['imageData']
else:
imageData = io.BytesIO(request.get_data())
img = Image.open(imageData)
results = predict_image(img)
return jsonify(results)
except Exception as e:
print("Par ici 1")
print('EXCEPTION:', str(e))
return 'Error processing image', 500
# Like the CustomVision.ai Prediction service /url route handles url's
# in the body of hte request of the form:
# { 'Url': '<http url>'}
@app.route('/url', methods=['POST'])
@app.route('/<project>/url', methods=['POST'])
@app.route('/<project>/url/nostore', methods=['POST'])
@app.route('/<project>/classify/iterations/<publishedName>/url', methods=['POST'])
@app.route('/<project>/classify/iterations/<publishedName>/url/nostore', methods=['POST'])
@app.route('/<project>/detect/iterations/<publishedName>/url', methods=['POST'])
@app.route('/<project>/detect/iterations/<publishedName>/url/nostore', methods=['POST'])
def predict_url_handler(project=None, publishedName=None):
try:
image_url = json.loads(request.get_data().decode('utf-8'))['url']
results = predict_url(image_url)
return jsonify(results)
except Exception as e:
print('EXCEPTION:', str(e))
return 'Error processing image'
if __name__ == '__main__':
# Load and intialize the model
initialize()
# Run the server
app.run(host='0.0.0.0', port=80)