Escreve o código o mais avançado possível para o desenvolvimento uma aplicação que, pela aplicação de um conjunto de algoritmos, permita a contabilização e identificação de resistências elétricas presentes num vídeo. Esta aplicação deverá ser capaz de segmentar as diferentes resistências (e apenas as resistências), identificando o seu valor (expressando-o em ohm) e localização relativa (qual a região da imagem ocupada por cada resistência) em cada frame do vídeo.
Em C++ e usando o openCV
Alguém consegue ajudar aqui? Não sei o que estou a fazer mal
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
// Função para identificar as bandas de cores em um resistor
vector<Rect> identifyColorBands(const Mat& roi) {
vector<Rect> bands;
Mat hsv, mask;
cvtColor(roi, hsv, COLOR_BGR2HSV);
// Definir faixas de cores para bandas de resistores
vector<Scalar> lower_bounds = {
Scalar(0, 70, 50), Scalar(10, 100, 100), Scalar(20, 100, 100), Scalar(30, 100, 100),
Scalar(50, 100, 100), Scalar(70, 100, 100), Scalar(90, 100, 100), Scalar(0, 0, 50)
};
vector<Scalar> upper_bounds = {
Scalar(10, 255, 255), Scalar(20, 255, 255), Scalar(30, 255, 255), Scalar(40, 255, 255),
Scalar(70, 255, 255), Scalar(90, 255, 255), Scalar(110, 255, 255), Scalar(180, 50, 200)
};
for (size_t i = 0; i < lower_bounds.size(); i++) {
inRange(hsv, lower_bounds[i], upper_bounds[i], mask);
vector<vector<Point>> contours;
findContours(mask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (const auto& contour : contours) {
Rect boundingBox = boundingRect(contour);
if (boundingBox.height > roi.rows / 3 && boundingBox.width < roi.cols / 3) {
bands.push_back(boundingBox);
}
}
}
// Ordenar as bandas de cores de acordo com a posição no eixo x
sort(bands.begin(), bands.end(), [](const Rect& a, const Rect& b) {
return a.x < b.x;
});
return bands;
}
// Função para detectar e rotular resistências
void detectAndLabelResistors(Mat& frame) {
Mat gray, blurred, binary, dilated;
// Converter para escala de cinza
cvtColor(frame, gray, COLOR_BGR2GRAY);
// Aplicar filtro gaussiano para suavizar a imagem
GaussianBlur(gray, blurred, Size(5, 5), 1.5);
// Binarizar a imagem usando limiarização global com Otsu
threshold(blurred, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
// Dilatar a imagem para conectar componentes
Mat kernel = getStructuringElement(MORPH_RECT, Size(5, 5));
dilate(binary, dilated, kernel);
// Encontrar contornos dos blobs
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(dilated, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// Desenhar contornos e rótulos nos blobs
for (size_t i = 0; i < contours.size(); i++) {
Rect boundingBox = boundingRect(contours[i]);
// Calcular a razão de aspecto do bounding box
float aspectRatio = (float)boundingBox.width / (float)boundingBox.height;
// Definir critérios para detectar um resistor
bool isResistor = (aspectRatio > 2.0) && (boundingBox.width > 30) && (boundingBox.height > 10) && (boundingBox.width < 300) && (boundingBox.height < 100);
if (isResistor) {
rectangle(frame, boundingBox, Scalar(0, 255, 0), 2);
Point labelPosition(boundingBox.x, boundingBox.y - 10);
putText(frame, "Resistor", labelPosition, FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 255, 0), 2);
// Identificar e rotular as bandas de cores
Mat roi = frame(boundingBox);
vector<Rect> colorBands = identifyColorBands(roi);
for (size_t j = 0; j < colorBands.size() && j < 3; j++) {
rectangle(roi, colorBands[j], Scalar(255, 0, 0), 2);
putText(roi, "Banda " + to_string(j + 1), colorBands[j].tl(), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 1);
}
}
}
}
int main() {
// Abrir o vídeo
VideoCapture cap("video_resistors.mp4");
if (!cap.isOpened()) {
cerr << "Erro ao abrir o vídeo!" << endl;
return -1;
}
// Configurar o escritor de vídeo
int frame_width = static_cast<int>(cap.get(CAP_PROP_FRAME_WIDTH));
int frame_height = static_cast<int>(cap.get(CAP_PROP_FRAME_HEIGHT));
VideoWriter video("processed_video.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 10, Size(frame_width, frame_height));
Mat frame;
while (cap.read(frame)) {
// Detectar e rotular resistências
detectAndLabelResistors(frame);
// Escrever o frame processado no vídeo de saída
video.write(frame);
// Exibir o frame com as resistências identificadas
imshow("Resistores Identificados", frame);
if (waitKey(30) >= 0) break;
}
cap.release();
video.release();
destroyAllWindows();
return 0;
}
…………………….
Luís Gonçalves is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1