Skip to content

Instantly share code, notes, and snippets.

@johnnyferreiradev
Created May 14, 2019 00:44
Show Gist options
  • Save johnnyferreiradev/e30b0d757512b68d81b7eb7f255f5c58 to your computer and use it in GitHub Desktop.
Save johnnyferreiradev/e30b0d757512b68d81b7eb7f255f5c58 to your computer and use it in GitHub Desktop.
Algoritmo para segmentação de imagens com binarização
#include <QCoreApplication>
#include <opencv2/opencv.hpp>
using namespace cv;
int binariza(int pixel, int nivel) {
if(pixel <= nivel) {
pixel = 0;
} else {
pixel = 255;
}
return pixel;
}
int porcentagem (Mat img, float porcent) {
int limiar;
Mat aux = img.clone();
for (limiar = 1; limiar < 255; limiar++) {
for(int i=0; i<img.rows; i++){
for(int j=0; j<img.cols; j++){
aux.at<uchar>(i,j) = binariza(img.at<uchar>(i,j), limiar);
}
}
int count_p, count_b;
for(int i=0; i<aux.rows; i++){
for(int j=0; j<aux.cols; j++){
if (aux.at<uchar>(i,j) == 0) {
count_p++;
} else {
count_b++;
}
}
}
float p;
p = count_p / (float) count_b;
p *= 100;
if (p >= porcent - 30 && p >= porcent + 30) {
break;
}
}
return limiar;
}
int main(){
Mat img = imread("/home/johnny/Documentos/Sistemas de Informacao/S4/PDI/Imagens/placa.jpg", 0);
Mat aux1 = img.clone();
Mat aux2 = img.clone();
Mat aux3 = img.clone();
int limiar;
limiar = porcentagem(img, 10);
for(int i=0; i<img.rows; i++){
for(int j=0; j<img.cols; j++){
aux1.at<uchar>(i,j) = binariza(img.at<uchar>(i,j), 128);
aux2.at<uchar>(i,j) = binariza(img.at<uchar>(i,j), limiar);
}
}
namedWindow("Limiarização de Nivel 90");
namedWindow("Limiarização Tom de Cinza Médio");
//namedWindow("Limiarização de Nivel 200");
imshow("Limiarização de Nivel 90", aux1);
imshow("Limiarização Tom de Cinza Médio", aux2);
//imshow("Limiarização de Nivel 200", aux3);
waitKey(0);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment