| 5 | #include <android/log.h> |
| 6 | #include <vector> |
| 7 | #include <utility> |
| 8 | #include <string> |
| 9 | #include <math.h> |
| 10 | #include <stdint.h> |
| 11 | #include <stdlib.h> |
| 12 | #include <stdio.h> |
| 13 | #include <string.h> |
| 14 | #include <libyuv.h> |
| 15 | #include "fast-edge.h" |
| 16 | #include "genann.h" |
| 17 |
| 18 | #ifndef max |
| 19 | #define max(a, b) (a>b ? a : b) |
| 20 | #define min(a, b) (a<b ? a : b) |
| 21 | #endif |
| 22 |
| 23 |
| 24 | #define TAG "ocr" |
| 25 | #define _LOG_WRAP(...) __VA_ARGS__ |
| 26 | #define LOGV(...) {__android_log_print(ANDROID_LOG_VERBOSE, TAG, _LOG_WRAP(__VA_ARGS__));} |
| 27 | #define LOGD(...) {__android_log_print(ANDROID_LOG_DEBUG, TAG, _LOG_WRAP(__VA_ARGS__));} |
| 28 | #define LOGI(...) {__android_log_print(ANDROID_LOG_INFO, TAG, _LOG_WRAP(__VA_ARGS__));} |
| 29 | #define LOGW(...) {__android_log_print(ANDROID_LOG_WARN, TAG, _LOG_WRAP(__VA_ARGS__));} |
| 30 | #define LOGE(...) {__android_log_print(ANDROID_LOG_ERROR, TAG, _LOG_WRAP(__VA_ARGS__));} |
| 31 |
| 32 | namespace ocr{ |
| 33 | struct line{ |
| 34 | double theta; |
| 35 | double r; |
| 36 | }; |
| 37 |
| 38 | std::vector<line> detectLines(struct image* img, int threshold){ |
| 39 | // The size of the neighbourhood in which to search for other local maxima |
| 40 | const int neighbourhoodSize = 4; |
| 41 |
| 42 | // How many discrete values of theta shall we check? |
| 43 | const int maxTheta = 180; |
| 44 |
| 45 | // Using maxTheta, work out the step |
| 46 | const double thetaStep = M_PI / maxTheta; |
| 47 |
| 48 | int width=img->width; |
| 49 | int height=img->height; |
| 50 | // Calculate the maximum height the hough array needs to have |
| 51 | int houghHeight = (int) (sqrt(2.0) * max(height, width)) / 2; |
| 52 |
| 53 | // Double the height of the hough array to cope with negative r values |
| 54 | int doubleHeight = 2 * houghHeight; |
| 55 |
| 56 | // Create the hough array |
| 57 | int* houghArray = new int[maxTheta*doubleHeight]; |
| 58 | memset(houghArray, 0, sizeof(int)*maxTheta*doubleHeight); |
| 59 |
| 60 | // Find edge points and vote in array |
| 61 | int centerX = width / 2; |
| 62 | int centerY = height / 2; |
| 63 |
| 64 | // Count how many points there are |
| 65 | int numPoints = 0; |
| 66 |
| 67 | // cache the values of sin and cos for faster processing |
| 68 | double* sinCache = new double[maxTheta]; |
| 69 | double* cosCache = new double[maxTheta]; |
| 70 | for (int t = 0; t < maxTheta; t++) { |
| 71 | double realTheta = t * thetaStep; |
| 72 | sinCache[t] = sin(realTheta); |
| 73 | cosCache[t] = cos(realTheta); |
| 74 | } |
| 75 |
| 76 | // Now find edge points and update the hough array |
| 77 | for (int x = 0; x < width; x++) { |
| 78 | for (int y = 0; y < height; y++) { |
| 79 | // Find non-black pixels |
| 80 | if ((img->pixel_data[y*width+x] & 0x000000ff) != 0) { |
| 81 | // Go through each value of theta |
| 82 | for (int t = 0; t < maxTheta; t++) { |
| 83 |
| 84 | //Work out the r values for each theta step |
| 85 | int r = (int) (((x - centerX) * cosCache[t]) + ((y - centerY) * sinCache[t])); |
| 86 |
| 87 | // this copes with negative values of r |
| 88 | r += houghHeight; |
| 89 |
| 90 | if (r < 0 || r >= doubleHeight) continue; |
| 91 |
| 92 | // Increment the hough array |
| 93 | houghArray[t*doubleHeight+r]++; |
| 94 |
| 95 | } |
| 96 |
| 97 | numPoints++; |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 |
| 102 | // Initialise the vector of lines that we'll return |
| 103 | std::vector<line> lines; |
| 104 |
| 105 | // Only proceed if the hough array is not empty |
| 106 | if (numPoints == 0){ |
| 107 | delete[] houghArray; |
| 108 | delete[] sinCache; |
| 109 | delete[] cosCache; |
| 110 | return lines; |
| 111 | } |
| 112 |
| 113 | // Search for local peaks above threshold to draw |
| 114 | for (int t = 0; t < maxTheta; t++) { |
| 115 | //loop: |
| 116 | for (int r = neighbourhoodSize; r < doubleHeight - neighbourhoodSize; r++) { |
| 117 |
| 118 | // Only consider points above threshold |
| 119 | if (houghArray[t*doubleHeight+r] > threshold) { |
| 120 |
| 121 | int peak = houghArray[t*doubleHeight+r]; |
| 122 |
| 123 | // Check that this peak is indeed the local maxima |
| 124 | for (int dx = -neighbourhoodSize; dx <= neighbourhoodSize; dx++) { |
| 125 | for (int dy = -neighbourhoodSize; dy <= neighbourhoodSize; dy++) { |
| 126 | int dt = t + dx; |
| 127 | int dr = r + dy; |
| 128 | if (dt < 0) dt = dt + maxTheta; |
| 129 | else if (dt >= maxTheta) dt = dt - maxTheta; |
| 130 | if (houghArray[dt*doubleHeight+dr] > peak) { |
| 131 | // found a bigger point nearby, skip |
| 132 | goto loop; |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 |
| 137 | // calculate the true value of theta |
| 138 | double theta = t * thetaStep; |
| 139 |
| 140 | // add the line to the vector |
| 141 | line l={theta, (double)r-houghHeight}; |
| 142 | lines.push_back(l); |
| 143 |
| 144 | } |
| 145 | loop: |
| 146 | continue; |
| 147 | } |
| 148 | } |
| 149 |
| 150 | delete[] houghArray; |
| 151 | delete[] sinCache; |
| 152 | delete[] cosCache; |
| 153 | return lines; |
| 154 |
| 155 | } |
| 156 |
| 157 | void binarizeBitmapPart(uint32_t* inPixels, unsigned char* outPixels, size_t width, size_t height, size_t inStride, size_t outStride){ |
| 158 | uint32_t histogram[256]={0}; |
| 159 | uint32_t intensitySum=0; |
| 160 | for(unsigned int y=0;y<height;y++){ |
| 161 | for(unsigned int x=0;x<width;x++){ |
| 162 | uint32_t px=inPixels[y*inStride/sizeof(uint32_t)+x]; |
| 163 | int l=(((px & 0xFF)+((px & 0xFF00) >> 8)+((px & 0xFF0000) >> 16))/3); |
| 164 | outPixels[y*outStride+x]=(unsigned char)l; |
| 165 | histogram[l]++; |
| 166 | intensitySum+=l; |
| 167 | } |
| 168 | } |
| 169 | int threshold=0; |
| 170 | double best_sigma = 0.0; |
| 171 |
| 172 | int first_class_pixel_count = 0; |
| 173 | int first_class_intensity_sum = 0; |
| 174 |
| 175 | for (int thresh = 0; thresh < 255; ++thresh) { |
| 176 | first_class_pixel_count += histogram[thresh]; |
| 177 | first_class_intensity_sum += thresh * histogram[thresh]; |
| 178 |
| 179 | double first_class_prob = first_class_pixel_count / (double) (width*height); |
| 180 | double second_class_prob = 1.0 - first_class_prob; |
| 181 |
| 182 | double first_class_mean = first_class_intensity_sum / (double) first_class_pixel_count; |
| 183 | double second_class_mean = (intensitySum - first_class_intensity_sum) |
| 184 | / (double) ((width*height) - first_class_pixel_count); |
| 185 |
| 186 | double mean_delta = first_class_mean - second_class_mean; |
| 187 |
| 188 | double sigma = first_class_prob * second_class_prob * mean_delta * mean_delta; |
| 189 |
| 190 | if (sigma > best_sigma) { |
| 191 | best_sigma = sigma; |
| 192 | threshold = thresh; |
| 193 | } |
| 194 | } |
| 195 |
| 196 | for(unsigned int y=0;y<height;y++){ |
| 197 | for(unsigned int x=0;x<width;x++){ |
| 198 | uint32_t px=inPixels[y*inStride/sizeof(uint32_t)+x]; |
| 199 | outPixels[y*outStride+x]=(px & 0xFF)<threshold && ((px & 0xFF00) >> 8)<threshold && ((px & 0xFF0000) >> 16)<threshold ? (unsigned char)255 : (unsigned char)0; |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 |
| 205 | extern "C" JNIEXPORT jintArray Java_org_telegram_messenger_MrzRecognizer_findCornerPoints(JNIEnv* env, jclass clasz, jobject bitmap){ |
| 206 | AndroidBitmapInfo info={0}; |
| 207 | if(AndroidBitmap_getInfo(env, bitmap, &info)!=ANDROID_BITMAP_RESULT_SUCCESS){ |
| 208 | return NULL; |
| 209 | } |
| 210 | if(info.format!=ANDROID_BITMAP_FORMAT_RGBA_8888){ |
| 211 | return NULL; |
| 212 | } |
| 213 | //LOGD("Bitmap info: %d x %d, stride %d", info.width, info.height, info.stride); |
| 214 | unsigned int width=info.width; |
| 215 | unsigned int height=info.height; |
| 216 | uint32_t* bitmapPixels; |
| 217 | if(AndroidBitmap_lockPixels(env, bitmap, reinterpret_cast<void**>(&bitmapPixels))!=ANDROID_BITMAP_RESULT_SUCCESS){ |
| 218 | LOGE("AndroidBitmap_lockPixels failed!"); |
| 219 | return NULL; |
| 220 | } |
| 221 | struct ocr::image imgIn, imgOut; |
| 222 | imgIn.width=imgOut.width=width; |
| 223 | imgIn.height=imgOut.height=height; |
| 224 | imgIn.pixel_data=(unsigned char*)malloc(width*height); |
| 225 | imgOut.pixel_data=(unsigned char*)calloc(width*height, 1); |
| 226 | for(unsigned int y=0;y<height;y++){ |
| 227 | for(unsigned int x=0;x<width;x++){ |
| 228 | uint32_t px=bitmapPixels[info.stride*y/sizeof(uint32_t)+x]; |
| 229 | imgIn.pixel_data[width*y+x]=(unsigned char) (((px & 0xFF)+((px & 0xFF00) >> 8)+((px & 0xFF0000) >> 16))/3); |
| 230 | } |
| 231 | } |
| 232 | AndroidBitmap_unlockPixels(env, bitmap); |
| 233 |
| 234 | ocr::canny_edge_detect(&imgIn, &imgOut); |
| 235 |
| 236 | std::vector<ocr::line> lines=ocr::detectLines(&imgOut, 100); |
| 237 | for(int i=0;i<width*height;i++){ |
| 238 | imgOut.pixel_data[i]/=2; |
| 239 | } |
| 240 | std::vector<std::vector<ocr::line>> parallelGroups; |
| 241 | for(int i=0;i<36;i++){ |
| 242 | parallelGroups.emplace_back(); |
| 243 | } |
| 244 | ocr::line* left=NULL; |
| 245 | ocr::line* right=NULL; |
| 246 | ocr::line* top=NULL; |
| 247 | ocr::line* bottom=NULL; |
| 248 | for(std::vector<ocr::line>::iterator l=lines.begin();l!=lines.end();){ |
| 249 | // remove lines at irrelevant angles |
| 250 | if(!(l->theta>M_PI*0.4 && l->theta<M_PI*0.6) && !(l->theta<M_PI*0.1 || l->theta>M_PI*0.9)){ |
| 251 | l=lines.erase(l); |
| 252 | continue; |
| 253 | } |
| 254 | // remove vertical lines close to the middle of the image |
| 255 | if((l->theta<M_PI*0.1 || l->theta>M_PI*0.9) && abs((int)l->r)<height/4){ |
| 256 | l=lines.erase(l); |
| 257 | continue; |
| 258 | } |
| 259 | // find the leftmost and rightmost lines |
| 260 | if(l->theta<M_PI*0.1 || l->theta>M_PI*0.9){ |
| 261 | double rk=l->theta<0.5 ? 1.0 : -1.0; |
| 262 | if(!left || left->r>l->r*rk){ |
| 263 | left=&*l; |
| 264 | } |
| 265 | if(!right || right->r<l->r*rk){ |
| 266 | right=&*l; |
| 267 | } |
| 268 | } |
| 269 | // group parallel-ish lines with 5-degree increments |
| 270 | parallelGroups[floor(l->theta/M_PI*36)].push_back(*l); |
| 271 | ++l; |
| 272 | } |
| 273 |
| 274 | // the text on the page tends to produce a lot of parallel lines - so we assume the top & bottom edges of the page |
| 275 | // are topmost & bottommost lines in the largest group of horizontal lines |
| 276 | std::vector<ocr::line>& largestParallelGroup=parallelGroups[0]; |
| 277 | for(std::vector<std::vector<ocr::line>>::iterator group=parallelGroups.begin();group!=parallelGroups.end();++group){ |
| 278 | if(largestParallelGroup.size()<group->size()) |
| 279 | largestParallelGroup=*group; |
| 280 | } |
| 281 |
| 282 | for(std::vector<ocr::line>::iterator l=largestParallelGroup.begin();l!=largestParallelGroup.end();++l){ |
| 283 | // If the image is horizontal, we assume it's just the data page or an ID card so we're going for the topmost line. |
| 284 | // If it's vertical, it likely contains both the data page and the page adjacent to it so we're going for the line that is closest to the center of the image. |
| 285 | // Nobody in their right mind is going to be taking vertical pictures of ID cards, right? |
| 286 | if(width>height){ |
| 287 | if(!top || top->r>l->r){ |
| 288 | top=&*l; |
| 289 | } |
| 290 | }else{ |
| 291 | if(!top || fabs(l->r)<fabs(top->r)){ |
| 292 | top=&*l; |
| 293 | } |
| 294 | } |
| 295 | if(!bottom || bottom->r<l->r){ |
| 296 | bottom=&*l; |
| 297 | } |
| 298 | } |
| 299 |
| 300 | jintArray result=NULL; |
| 301 | if(top && bottom && left && right){ |
| 302 | //LOGI("bottom theta %f", bottom->theta); |
| 303 | if(bottom->theta>1.65 || bottom->theta<1.55){ |
| 304 | //LOGD("left: %f, right: %f\n", left->r, right->r); |
| 305 | int points[8]={0}; |
| 306 | bool foundTopLeft=false, foundTopRight=false, foundBottomLeft=false, foundBottomRight=false; |
| 307 | double centerX=width/2.0; |
| 308 | double centerY=height/2.0; |
| 309 | double ltsin=sin(left->theta); |
| 310 | double ltcos=cos(left->theta); |
| 311 | double rtsin=sin(right->theta); |
| 312 | double rtcos=cos(right->theta); |
| 313 | double ttsin=sin(top->theta); |
| 314 | double ttcos=cos(top->theta); |
| 315 | double btsin=sin(bottom->theta); |
| 316 | double btcos=cos(bottom->theta); |
| 317 | for (int y = -((int)height)/4; y < (int)height; y++) { |
| 318 | int lx = (int) (((left->r - ((y - centerY) * ltsin)) / ltcos) + centerX); |
| 319 | int ty = (int) (((top->r - ((lx - centerX) * ttcos)) / ttsin) + centerY); |
| 320 | if(ty==y){ |
| 321 | points[0]=lx; |
| 322 | points[1]=y; |
| 323 | foundTopLeft=true; |
| 324 | if(foundTopRight) |
| 325 | break; |
| 326 | } |
| 327 | int rx = (int) (((right->r - ((y - centerY) * rtsin)) / rtcos) + centerX); |
| 328 | ty = (int) (((top->r - ((rx - centerX) * ttcos)) / ttsin) + centerY); |
| 329 | if(ty==y){ |
| 330 | points[2]=rx; |
| 331 | points[3]=y; |
| 332 | foundTopRight=true; |
| 333 | if(foundTopLeft) |
| 334 | break; |
| 335 | } |
| 336 | } |
| 337 | for (int y = height+height/3; y>=0; y--) { |
| 338 | int lx = (int) (((left->r - ((y - centerY) * ltsin)) / ltcos) + centerX); |
| 339 | int by = (int) (((bottom->r - ((lx - centerX) * btcos)) / btsin) + centerY); |
| 340 | if(by==y){ |
| 341 | points[4]=lx; |
| 342 | points[5]=y; |
| 343 | foundBottomLeft=true; |
| 344 | if(foundBottomRight) |
| 345 | break; |
| 346 | } |
| 347 | int rx = (int) (((right->r - ((y - centerY) * rtsin)) / rtcos) + centerX); |
| 348 | by = (int) (((bottom->r - ((rx - centerX) * btcos)) / btsin) + centerY); |
| 349 | if(by==y){ |
| 350 | points[6]=rx; |
| 351 | points[7]=y; |
| 352 | foundBottomRight=true; |
| 353 | if(foundBottomLeft) |
| 354 | break; |
| 355 | } |
| 356 | } |
| 357 | if(foundTopLeft && foundTopRight && foundBottomLeft && foundBottomRight){ |
| 358 | result=env->NewIntArray(8); |
| 359 | env->SetIntArrayRegion(result, 0, 8, points); |
| 360 | //LOGD("Points: (%d %d) (%d %d) (%d %d) (%d %d)", points[0], points[1], points[2], points[3], points[4], points[5], points[6], points[7]); |
| 361 | } |
| 362 | }else{ |
| 363 | //LOGD("No perspective correction needed"); |
| 364 | } |
| 365 | } |
| 366 |
| 367 | free(imgIn.pixel_data); |
| 368 | free(imgOut.pixel_data); |
| 369 |
| 370 | return result; |
| 371 | } |
| 372 |
| 373 | extern "C" JNIEXPORT jobjectArray Java_org_telegram_messenger_MrzRecognizer_binarizeAndFindCharacters(JNIEnv* env, jclass clasz, jobject inBmp, jobject outBmp){ |
| 374 | AndroidBitmapInfo inInfo={0}, outInfo={0}; |
| 375 | if(AndroidBitmap_getInfo(env, inBmp, &inInfo)!=ANDROID_BITMAP_RESULT_SUCCESS || AndroidBitmap_getInfo(env, outBmp, &outInfo)!=ANDROID_BITMAP_RESULT_SUCCESS){ |
| 376 | LOGE("AndroidBitmap_getInfo failed"); |
| 377 | return NULL; |
| 378 | } |
| 379 | if(inInfo.width!=outInfo.width || inInfo.height!=outInfo.height || inInfo.format!=ANDROID_BITMAP_FORMAT_RGBA_8888 || outInfo.format!=ANDROID_BITMAP_FORMAT_A_8){ |
| 380 | LOGE("bitmap validation failed"); |
| 381 | return NULL; |
| 382 | } |
| 383 | unsigned int height=inInfo.height; |
| 384 | unsigned int width=inInfo.width; |
| 385 | uint32_t* inPixels; |
| 386 | unsigned char* outPixels; |
| 387 | if(AndroidBitmap_lockPixels(env, inBmp, reinterpret_cast<void**>(&inPixels))!=ANDROID_BITMAP_RESULT_SUCCESS){ |
| 388 | LOGE("AndroidBitmap_lockPixels failed"); |
| 389 | return NULL; |
| 390 | } |
| 391 | if(AndroidBitmap_lockPixels(env, outBmp, reinterpret_cast<void**>(&outPixels))!=ANDROID_BITMAP_RESULT_SUCCESS){ |
| 392 | AndroidBitmap_unlockPixels(env, inBmp); |
| 393 | LOGE("AndroidBitmap_lockPixels failed"); |
| 394 | return NULL; |
| 395 | } |
| 396 |
| 397 | for(unsigned int y=0;y<height;y+=120){ |
| 398 | for(unsigned int x=0; x<width; x+=120){ |
| 399 | int partWidth=x+120<width ? 120 : (width-x); |
| 400 | int partHeight=y+120<height ? 120 : (height-y); |
| 401 | ocr::binarizeBitmapPart(&inPixels[(y*inInfo.stride/sizeof(uint32_t))+x], outPixels+(y*outInfo.stride)+x, partWidth, partHeight, inInfo.stride, outInfo.stride); |
| 402 | } |
| 403 | } |
| 404 |
| 405 | // remove any single pixels without adjacent ones - these are usually noise |
| 406 | for(unsigned int y=height/2;y<height-1;y++){ |
| 407 | unsigned int yOffset=y*outInfo.stride; |
| 408 | unsigned int yOffsetPrev=(y-1)*outInfo.stride; |
| 409 | unsigned int yOffsetNext=(y+1)*outInfo.stride; |
| 410 | for(unsigned int x=1;x<width-1;x++){ |
| 411 | int pixelCount=0; |
| 412 | if(outPixels[yOffsetPrev+x-1]!=0) |
| 413 | pixelCount++; |
| 414 | if(outPixels[yOffsetPrev+x]!=0) |
| 415 | pixelCount++; |
| 416 | if(outPixels[yOffsetPrev+x+1]!=0) |
| 417 | pixelCount++; |
| 418 |
| 419 | if(outPixels[yOffset+x-1]!=0) |
| 420 | pixelCount++; |
| 421 | if(outPixels[yOffset+x]!=0) |
| 422 | pixelCount++; |
| 423 | if(outPixels[yOffset+x+1]!=0) |
| 424 | pixelCount++; |
| 425 |
| 426 | if(outPixels[yOffsetNext+x-1]!=0) |
| 427 | pixelCount++; |
| 428 | if(outPixels[yOffsetNext+x]!=0) |
| 429 | pixelCount++; |
| 430 | if(outPixels[yOffsetNext+x+1]!=0) |
| 431 | pixelCount++; |
| 432 |
| 433 | if(pixelCount<3) |
| 434 | outPixels[yOffset+x]=0; |
| 435 | } |
| 436 | } |
| 437 |
| 438 | // search from the bottom up for continuous areas of mostly empty pixels |
| 439 | unsigned int consecutiveEmptyRows=0; |
| 440 | std::vector<std::pair<unsigned int, unsigned int>> emptyAreaYs; |
| 441 | for(unsigned int y=height-1;y>=height/2;y--){ |
| 442 | unsigned int consecutiveEmptyPixels=0; |
| 443 | unsigned int maxEmptyPixels=0; |
| 444 | for(unsigned int x=0;x<width;x++){ |
| 445 | if(outPixels[y*outInfo.stride+x]==0){ |
| 446 | consecutiveEmptyPixels++; |
| 447 | }else{ |
| 448 | maxEmptyPixels=max(maxEmptyPixels, consecutiveEmptyPixels); |
| 449 | consecutiveEmptyPixels=0; |
| 450 | } |
| 451 | } |
| 452 | maxEmptyPixels=max(maxEmptyPixels, consecutiveEmptyPixels); |
| 453 | if(maxEmptyPixels>width/10*8){ |
| 454 | consecutiveEmptyRows++; |
| 455 | }else if(consecutiveEmptyRows>0){ |
| 456 | emptyAreaYs.emplace_back(y, y+consecutiveEmptyRows); |
| 457 | consecutiveEmptyRows=0; |
| 458 | } |
| 459 | } |
| 460 |
| 461 | std::vector<jobjectArray> result; |
| 462 | jclass rectClass=env->FindClass("android/graphics/Rect"); |
| 463 | jmethodID rectConstructor=env->GetMethodID(rectClass, "<init>", "(IIII)V"); |
| 464 | // using the areas found above, do the same thing but horizontally and between them in an attempt to ultimately find the bounds of the MRZ characters |
| 465 | for(std::vector<std::pair<unsigned int, unsigned int>>::iterator p=emptyAreaYs.begin();p!=emptyAreaYs.end();++p){ |
| 466 | std::vector<std::pair<unsigned int, unsigned int>>::iterator next=std::next(p); |
| 467 | if(next!=emptyAreaYs.end()){ |
| 468 | unsigned int lineHeight=p->first-next->second; |
| 469 | // An MRZ line can't really be this thin so this probably isn't one |
| 470 | if(lineHeight<10) |
| 471 | continue; |
| 472 | unsigned int consecutiveEmptyCols=0; |
| 473 | std::vector<std::pair<unsigned int, unsigned int>> emptyAreaXs; |
| 474 | for(unsigned int x=0;x<width;x++){ |
| 475 | unsigned int consecutiveEmptyPixels=0; |
| 476 | unsigned int maxEmptyPixels=0; |
| 477 | unsigned int bottomFilledPixels=0; // count these separately because we want those L's recognized correctly |
| 478 | for(unsigned int y=next->second;y<p->first;y++){ |
| 479 | if(outPixels[y*outInfo.stride+x]==0){ |
| 480 | consecutiveEmptyPixels++; |
| 481 | }else{ |
| 482 | maxEmptyPixels=max(maxEmptyPixels, consecutiveEmptyPixels); |
| 483 | consecutiveEmptyPixels=0; |
| 484 | if(y>p->first-3) |
| 485 | bottomFilledPixels++; |
| 486 | } |
| 487 | } |
| 488 | maxEmptyPixels=consecutiveEmptyPixels; |
| 489 | if(lineHeight-maxEmptyPixels<=lineHeight/15 && bottomFilledPixels==0){ |
| 490 | consecutiveEmptyCols++; |
| 491 | }else if(consecutiveEmptyCols>0){ |
| 492 | emptyAreaXs.emplace_back(x-consecutiveEmptyCols, x); |
| 493 | consecutiveEmptyCols=0; |
| 494 | } |
| 495 | } |
| 496 | if(consecutiveEmptyCols>0){ |
| 497 | emptyAreaXs.emplace_back(width-consecutiveEmptyCols, width); |
| 498 | } |
| 499 | if(emptyAreaXs.size()>30){ |
| 500 | bool foundLeftPadding=false; |
| 501 | std::vector<jobject> rects; |
| 502 | for(std::vector<std::pair<unsigned int, unsigned int>>::iterator h=emptyAreaXs.begin();h!=emptyAreaXs.end();++h){ |
| 503 | std::vector<std::pair<unsigned int, unsigned int>>::iterator nextH=std::next(h); |
| 504 | if(!foundLeftPadding && h->second-h->first>width/35){ |
| 505 | foundLeftPadding=true; |
| 506 | }else if(foundLeftPadding && h->second-h->first>width/30){ |
| 507 | if(rects.size()>=30){ |
| 508 | break; |
| 509 | }else{ |
| 510 | // restart the search because now we've (hopefully) found the real padding |
| 511 | rects.erase(rects.begin(), rects.end()); |
| 512 | } |
| 513 | } |
| 514 | if(nextH!=emptyAreaXs.end() && foundLeftPadding){ |
| 515 | unsigned int top=next->second; |
| 516 | unsigned int bottom=p->first; |
| 517 | // move the top and bottom edges towards each other as part of normalization |
| 518 | for(unsigned int y=top;y<bottom;y++){ |
| 519 | bool found=false; |
| 520 | for(unsigned int x=h->second; x<nextH->first; x++){ |
| 521 | if(outPixels[y*outInfo.stride+x]!=0){ |
| 522 | top=y; |
| 523 | found=true; |
| 524 | break; |
| 525 | } |
| 526 | } |
| 527 | if(found) |
| 528 | break; |
| 529 | } |
| 530 | for(unsigned int y=bottom;y>top;y--){ |
| 531 | bool found=false; |
| 532 | for(unsigned int x=h->second; x<nextH->first; x++){ |
| 533 | if(outPixels[y*outInfo.stride+x]!=0){ |
| 534 | bottom=y; |
| 535 | found=true; |
| 536 | break; |
| 537 | } |
| 538 | } |
| 539 | if(found) |
| 540 | break; |
| 541 | } |
| 542 | if(bottom-top<lineHeight/4) |
| 543 | continue; |
| 544 | if(rects.size()<44){ |
| 545 | jobject rect=env->NewObject(rectClass, rectConstructor, h->second, top, nextH->first, bottom); |
| 546 | rects.push_back(rect); |
| 547 | } |
| 548 | } |
| 549 | } |
| 550 | jobjectArray lineArray=env->NewObjectArray(static_cast<jsize>(rects.size()), rectClass, NULL); |
| 551 | int i=0; |
| 552 | for(std::vector<jobject>::iterator r=rects.begin();r!=rects.end();++r){ |
| 553 | env->SetObjectArrayElement(lineArray, i, *r); |
| 554 | i++; |
| 555 | } |
| 556 | result.push_back(lineArray); |
| 557 | if((rects.size()>=44 && result.size()==2) || (rects.size()>=30 && result.size()==3)){ |
| 558 | break; |
| 559 | } |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 |
| 564 | AndroidBitmap_unlockPixels(env, inBmp); |
| 565 | AndroidBitmap_unlockPixels(env, outBmp); |
| 566 |
| 567 | if(result.empty()) |
| 568 | return NULL; |
| 569 |
| 570 | jobjectArray resultArray=env->NewObjectArray(static_cast<jsize>(result.size()), env->GetObjectClass(result[0]), NULL); |
| 571 | int i=0; |
| 572 | for(std::vector<jobjectArray>::iterator a=result.begin();a!=result.end();++a){ |
| 573 | env->SetObjectArrayElement(resultArray, static_cast<jsize>(result.size()-i-1), *a); |
| 574 | i++; |
| 575 | } |
| 576 | return resultArray; |
| 577 | } |
| 578 |
| 579 | extern "C" JNIEXPORT jstring Java_org_telegram_messenger_MrzRecognizer_performRecognition(JNIEnv* env, jclass clasz, jobject bitmap, jint numRows, jint numCols, jobject jAssetManager){ |
| 580 | AAssetManager* assets=AAssetManager_fromJava(env, jAssetManager); |
| 581 | AAsset* nnData=AAssetManager_open(assets, "secureid_ocr_nn.dat", AASSET_MODE_STREAMING); |
| 582 | if(!nnData){ |
| 583 | LOGE("AAssetManager_open failed"); |
| 584 | return NULL; |
| 585 | } |
| 586 | struct genann* ann=genann_init(150, 1, 90, 37); |
| 587 | AAsset_read(nnData, ann->weight, sizeof(double)*ann->total_weights); |
| 588 | AAsset_close(nnData); |
| 589 | std::string res; |
| 590 | const char* alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890<"; |
| 591 | AndroidBitmapInfo info; |
| 592 | unsigned char* pixels; |
| 593 | AndroidBitmap_getInfo(env, bitmap, &info); |
| 594 | if(AndroidBitmap_lockPixels(env, bitmap, reinterpret_cast<void**>(&pixels))!=ANDROID_BITMAP_RESULT_SUCCESS){ |
| 595 | LOGE("AndroidBitmap_lockPixels failed"); |
| 596 | genann_free(ann); |
| 597 | return NULL; |
| 598 | } |
| 599 | double nnInput[150]; |
| 600 | for(int row=0;row<numRows;row++){ |
| 601 | for(int col=0;col<numCols;col++){ |
| 602 | unsigned int offX=static_cast<unsigned int>(col*10); |
| 603 | unsigned int offY=static_cast<unsigned int>(row*15); |
| 604 | for(unsigned int y=0;y<15;y++){ |
| 605 | for(unsigned int x=0;x<10;x++){ |
| 606 | nnInput[y*10+x]=(double)pixels[(offY+y)*info.stride+offX+x]/255.0; |
| 607 | } |
| 608 | } |
| 609 | const double* nnOut=genann_run(ann, nnInput); |
| 610 | unsigned int bestIndex=0; |
| 611 | for(unsigned int i=0;i<37;i++){ |
| 612 | if(nnOut[i]>nnOut[bestIndex]) |
| 613 | bestIndex=i; |
| 614 | } |
| 615 | res+=alphabet[bestIndex]; |
| 616 | } |
| 617 | if(row!=numRows-1) |
| 618 | res+="\n"; |
| 619 | } |
| 620 | genann_free(ann); |
| 621 | return env->NewStringUTF(res.c_str()); |
| 622 | } |
| 623 |
| 624 | extern "C" JNIEXPORT void Java_org_telegram_messenger_MrzRecognizer_setYuvBitmapPixels(JNIEnv* env, jclass clasz, jobject bitmap, jbyteArray jpixels){ |
| 625 | jbyte* _pixels=env->GetByteArrayElements(jpixels, NULL); |
| 626 | uint8_t* pixels=reinterpret_cast<uint8_t*>(_pixels); |
| 627 |
| 628 | AndroidBitmapInfo info; |
| 629 | uint32_t* bpixels; |
| 630 | if(AndroidBitmap_getInfo(env, bitmap, &info)==ANDROID_BITMAP_RESULT_SUCCESS){ |
| 631 | if(info.format==ANDROID_BITMAP_FORMAT_RGBA_8888){ |
| 632 | if(AndroidBitmap_lockPixels(env, bitmap, reinterpret_cast<void**>(&bpixels))==ANDROID_BITMAP_RESULT_SUCCESS){ |
| 633 | libyuv::NV12ToARGB(pixels, info.width, pixels+info.width*info.height, info.width, reinterpret_cast<uint8_t*>(bpixels), info.stride, info.width, info.height); |
| 634 | AndroidBitmap_unlockPixels(env, bitmap); |
| 635 | } |
| 636 | } |
| 637 | } |
| 638 |
| 639 | env->ReleaseByteArrayElements(jpixels, _pixels, JNI_ABORT); |
| 640 | } |