1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| void correctImage(unsigned char *nv21, int width, int height, unsigned char *dest) {
int resizeWidth = width/2; int resizeHeight = height/2;
Mat imgMat(height * 3 / 2, width, CV_8UC1, nv21); Mat grayMat(height, width, CV_8UC1); Mat resultMat(height, width, CV_8UC1,dest); Mat innerMat(resizeHeight, resizeWidth, CV_8UC1); Mat binMat(resizeHeight, resizeWidth, CV_8UC1);
cvtColor(imgMat, grayMat, CV_YUV420sp2GRAY);
resize(grayMat, innerMat, Size(resizeWidth, resizeHeight));
int blockSize = 3; int constValue = 5; const int maxVal = 255;
adaptiveThreshold(innerMat, binMat, maxVal,ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, blockSize, constValue);
int rectWidth = resizeWidth / 5; int rectHeight = resizeHeight / 5; int centerX = resizeWidth / 2, centerY = resizeHeight / 2;
Mat element = getStructuringElement(2, Size(7, 7));
for (int i = 0; i < 2; i++) { erode(innerMat, innerMat, element); i++; }
erode(innerMat, binMat, element); binMat = innerMat - binMat;
vector<Vec2f> lines; HoughLines(binMat, lines, 1, CV_PI / 150, 90, 0, 0); LOGV("OpenCV_CorrectImage寻找边线,边线数量:%d", lines.size());
int lineNum = lines.size() > 8 ? 8 : lines.size(); float sum = 0;
int num = 0; for (int i = 0; i < lineNum; i++) { float theta = lines[i][1];
if ((theta >= 0 && theta <= 0.2618) || (theta >= 1.3963 && theta <= 1.7453) || (theta >= 2.967 && theta <= 3.1416)) { } else { if (theta >= 1.5708) theta = theta - 1.5708; LOGV("OpenCV_CorrectImage寻找边线,角度:%f", theta); sum += theta; num += 1; } }
if (num > 0) { float average = sum / num; double angle = average / CV_PI * 180; LOGV("OpenCV_CorrectImage寻找边线,角度:%f", angle);
if (angle > 5) { Point2f center; center.x = float(width / 2.0); center.y = float(height / 2.0); Mat M = getRotationMatrix2D(center, angle, 1); warpAffine(grayMat, resultMat, M, resultMat.size(), 1, 0, Scalar(255)); LOGV("OpenCV_CorrectImage角度变换完成"); } } }
|