Guest User

Kotlin / Python code

a guest
Mar 20th, 2024
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.56 KB | Source Code | 0 0
  1. for(cnt in contours){
  2. val boundRect: Rect = Imgproc.boundingRect(cnt)
  3. if (boundRect.width > 90 && boundRect.height > 90 && boundRect.x != 0 && boundRect.y != 0){
  4. // Draw rectangles
  5. val x = boundRect.x.toDouble() - 30
  6. val y = boundRect.y.toDouble() - 30
  7. val w = boundRect.width.toDouble() + 30
  8. val h = boundRect.height.toDouble() + 30
  9.  
  10. Imgproc.rectangle(tmp, Point(x, y),
  11. Point(x + w, y + h),
  12. Scalar(0.0,255.0,0.0), 3)
  13.  
  14. // Extract bounding images, resize, and normalise
  15. val image_roi = Mat(tmp, boundRect)
  16. Imgproc.cvtColor(image_roi, image_roi, Imgproc.COLOR_RGB2GRAY)
  17. Imgproc.GaussianBlur(image_roi, image_roi, Size(3.0,3.0), 0.0)
  18. Imgproc.dilate(image_roi, image_roi, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, Size(4.0, 4.0)))
  19. Imgproc.threshold(image_roi, image_roi, 90.0, 255.0, Imgproc.THRESH_BINARY);
  20. Imgproc.resize(image_roi, image_roi, Size(28.0,28.0))
  21. Core.normalize(image_roi, image_roi, 0.0, 255.0, Core.NORM_MINMAX);
  22. image_roi.convertTo(image_roi, CvType.CV_8UC1)
  23. extracted.add(image_roi)
  24. }
  25.  
  26. }
  27.  
  28. This extracts and process the images. It's a bit messy. It extracts correctly, and seems to process it decently.
  29.  
  30. for (img in extracted) {
  31. val tensorBuffer = extractBytes(img)
  32. val outputs = model.process(tensorBuffer)
  33. val outputFeature0 = outputs.outputFeature0AsTensorBuffer
  34. val conf = outputFeature0.floatArray
  35. out += getLanguageText(conf, numbers)
  36.  
  37. }
  38.  
  39.  
  40. In another function, images are processed.
  41.  
  42. private fun extractBytes(img: Mat): TensorBuffer{
  43. val inputFeature = TensorBuffer.createFixedSize(intArrayOf(1, 28, 28, 1), DataType.FLOAT32)
  44. val byteBuffer = ByteBuffer.allocateDirect(28 * 28 * 4) // 4 bytes per float
  45. byteBuffer.order(ByteOrder.nativeOrder())
  46. byteBuffer.rewind()
  47.  
  48. for (i in 0 until 28) {
  49. for (j in 0 until 28) {
  50. val temp = img.get(i, j)[0].toFloat() // Assuming single-channel (gray)
  51. byteBuffer.putFloat(temp)
  52. }
  53. }
  54.  
  55. inputFeature.loadBuffer(byteBuffer)
  56. return inputFeature
  57. }
  58. Changing from opencv Mat to Tensorbuffer.
  59.  
  60. private fun getLanguageText(conf: FloatArray, numbers: Array<String>): String {
  61. return numbers[conf.indices.maxBy {conf[it]}]
  62. }
  63.  
  64. This just gets the maximum value of the conf array.
  65.  
  66.  
  67. Python code:
  68. def extractText(dirs):
  69. images = []
  70. # Read the original image
  71. img = cv2.imread(dirs[0])
  72.  
  73. # Convert to grayscale, blur, and get threshold
  74. img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  75. blur = cv2.GaussianBlur(img_gray, (3,3), 0)
  76. thresh = cv2.threshold(blur, 100, 255, cv2.THRESH_BINARY)[1]
  77.  
  78.  
  79. # Find contours
  80. cnts, hierarchy = cv2.findContours(image=thresh, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_SIMPLE)
  81. #img_copy = img.copy()
  82.  
  83. # From contours, find bounding boxes with ROI (region of interest)
  84. for contour in cnts:
  85. (x,y,w,h) = cv2.boundingRect(contour)
  86. if w > 90 and h > 90 and x != 0 and y != 0:
  87. # Pre-processing
  88. img_ = img[y-20:y+h+20, x-15:x+w+20]
  89. #img_copy = cv2.rectangle(img_copy, (x-5, y-5), (x+w+5, y+h+5), (0, 255, 0), 2)
  90.  
  91. # Blur the image for better edge detection
  92. img_gray = cv2.cvtColor(img_, cv2.COLOR_BGR2GRAY)
  93. img_invert = cv2.bitwise_not(img_gray)
  94. img_ = cv2.resize(img_invert, (28, 28))
  95. img_blur = cv2.GaussianBlur(img_, (3,3), 0)
  96. _, img_ts = cv2.threshold(img_blur, 90, 255, cv2.THRESH_BINARY)
  97.  
  98.  
  99. # Add to array
  100. img_ = np.asarray(img_ts, dtype=np.float32)/255.0
  101. images.append(img_)
  102. return np.array(images)
  103.  
  104. def predictExtractedText(data, model):
  105. # Load model
  106. model = tf.keras.models.load_model(model)
  107.  
  108.  
  109. # run prediction
  110. prediction = model.predict(data)
  111.  
  112. # Plot data
  113. plt.figure(1)
  114. #nko_numbers = "0߁߂߃߄߅߆߇߈߉"
  115. nko_numbers = "0123456789.-+wxyz/="
  116. for index in range(0, len(prediction)):
  117. plt.subplot(5,5,index+1)
  118. plt.title(f"Number: {nko_numbers[np.argmax(prediction[index])]}")
  119. img = np.asarray(images[index]).squeeze()
  120. plt.axis('off')
  121. plt.imshow(img)
  122. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment