Мне нужно обнаруживать объекты, а также пустые области, т. е. промежутки между эти объекты.
Следующий код app.py отмечает обнаруженные объекты и промежутки между ними:
Код: Выделить всё
import os
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
import cv2
import numpy as np
import matplotlib.pyplot as plt
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads/'
# Initialize Azure Computer Vision client
endpoint = os.getenv('AZURE_COMPUTER_VISION_ENDPOINT')
key = os.getenv('AZURE_COMPUTER_VISION_KEY')
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(key))
def preprocess_image(image_path):
"""
Preprocess the image to detect edges.
"""
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
return edges
def analyze_image(filepath):
"""
Analyze the uploaded image using Azure Computer Vision and detect objects,
and empty areas.
"""
with open(filepath, "rb") as image_contents:
results = computervision_client.analyze_image_in_stream(image_contents, visual_features=[VisualFeatureTypes.objects])
image = cv2.imread(filepath)
height, width, _ = image.shape
empty_areas = []
bounding_boxes = []
# Analyze detected objects
confidence_threshold = 0.5
shelves = {}
num_shelves = 5
for obj in results.objects:
if obj.confidence > confidence_threshold:
left = int(obj.rectangle.x)
top = int(obj.rectangle.y)
right = left + int(obj.rectangle.w)
bottom = top + int(obj.rectangle.h)
bounding_boxes.append((left, top, right, bottom))
row_key = (top // (height // num_shelves))
if row_key not in shelves:
shelves[row_key] = []
shelves[row_key].append((left, top, right, bottom))
# Detect empty areas between objects
gap_threshold = 50
for row_key, objects in shelves.items():
objects.sort(key=lambda x: x[0])
for i in range(len(objects) - 1):
_, _, right1, _ = objects[i]
left2, _, _, _ = objects[i + 1]
gap_width = left2 - right1
if gap_width > gap_threshold:
empty_areas.append((right1, row_key * (height // num_shelves), left2, (row_key + 1) * (height // num_shelves)))
# Create an output image with bounding boxes
fig, ax = plt.subplots()
ax.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
# Draw bounding boxes for objects
for (left, top, right, bottom) in bounding_boxes:
rect = plt.Rectangle((left, top), right - left, bottom - top, edgecolor='g', facecolor='none')
ax.add_patch(rect)
# Draw bounding boxes for empty areas
for (left, top, right, bottom) in empty_areas:
rect = plt.Rectangle((left, top), right - left, bottom - top, edgecolor='r', facecolor='none')
ax.add_patch(rect)
# Save the output image
result_filepath = os.path.join(app.config['UPLOAD_FOLDER'], 'result_' + os.path.basename(filepath))
plt.savefig(result_filepath)
plt.close()
return {
'bounding_boxes': bounding_boxes,
'empty_areas': empty_areas,
'image_url': result_filepath
}
@app.route('/', methods=['GET', 'POST'])
def index():
"""
Handle the upload of the image and display analysis results.
"""
if request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file:
filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(filepath)
results = analyze_image(filepath)
return render_template('result.html', results=results)
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)
Эти файлы в сочетании с обновленным приложением .py теперь будет обрабатывать обнаружение объектов и обнаружение пробелов. Однако я не могу правильно идентифицировать и пометить все объекты, а затем обнаружить промежутки между ними.
Изображение, используемое для анализа, прилагается. Ниже приведена ссылка для справки:
https://learn.microsoft.com/en-us/azure ... lf-analyze
Какие дополнительные изменения я могу внести в функцию анализ_изображения, чтобы правильно определить промежутки между объектами?

Подробнее здесь: https://stackoverflow.com/questions/788 ... etrained-m