【问题标题】:How to do Tesseract Ocr on stored image of Mongo DB如何在存储的 Mongodb 图像上进行 Tesseract Ocr
【发布时间】:2019-11-14 19:18:58
【问题描述】:

我已将图像作为二进制数据存储在 Mongodb 中,无法对其执行 ocr。我尝试了两种不同的方式。

  1. 我被单独使用,@Getmapping+@Asyn 根据对象 ID 获取图像。
  2. 第二个被用作基于 Mongodb 的 Uri 的独立程序 [public static void main]。

两个案例都无法做到这一点。 有谁知道如何以正确的方式做到这一点?

public class User {
    @Id
    private String id;  
    private String name;    
    private Binary image;}} getters & setters , constructors

CONTROLLER [非常适合作为二进制数据上传图像和检索图像]

@PostMapping("/upload")
User createUser(@RequestParam String name, @RequestParam MultipartFile file) throws IOException 
{   User user = new User();
    user.setName(name);
    user.setImage(new Binary(file.getBytes()));     
    return userRepository.save(user);
}   
@GetMapping("/retrive")
String getImage(@RequestParam String id) {  
    Optional<User> user = userRepository.findById(id);
    Encoder encoder = Base64.getEncoder();      
    return encoder.encodeToString(user.get().getImage().getData()); 
}

用于 OCR 的控制器 [结果在邮递员中显示 200 OK 但未执行来自 mongodb 的文本]

 @Bean(name = "threadPoolTaskExecutor")
 public Executor threadPoolTaskExecutor()
  { return new ThreadPoolTaskExecutor();    
   }


@Async("threadPoolTaskExecutor")    
@GetMapping("/image")   
public String asyncMethodWithConfiguredExecutor(@RequestParam String id) 
{   
    System.out.println("Execute method" + Thread.currentThread().getId());      
    Optional<User> user = userRepository.findById(id);      
    ITesseract instance = new Tesseract();          
    try {

        ByteArrayInputStream bais = new ByteArrayInputStream(user.get().getImage().getData());
        BufferedImage bufferImg = ImageIO.read(bais);           
        String imgText = instance.doOCR(bufferImg);         
        return imgText;
                }
    catch (Exception e) 
    {
        return "Error while reading image";
    }   }

2。 MAIN FUCTION [我的第二种方式-结果“ocr 无法读取的不受支持的图像”]

@SpringBootApplication
public class StackoverflowApplication 
{   
public static void main(String[] args) throws IOException 
{       
SpringApplication.run(StackoverflowApplication.class, args);    
Mongo mongodb = new MongoClient("localhost", 27017);                
DB db = mongodb.getDB("test-db");   
DBCollection collection = db.getCollection("user");     
File image = new File("mongodb://localhost:27017//test-db//user");
 Tesseract tessInst = new Tesseract();     
 tessInst.setDatapath("C:\\Program Files (x86)\\Tesseract-OCR\\tessdata");    
    try {
          String result= tessInst.doOCR(image);
          System.out.println(result);
       } catch (TesseractException a) {
          System.err.println(a.getMessage());   
    }   } }

image1 image 2

【问题讨论】:

    标签: java spring mongodb ocr tesseract


    【解决方案1】:

    您应该考虑使用名为 Spring Content 的 Mongo 社区项目来存储内容。 Spring Content 之于非结构化数据(文档、视频、图像),Spring Data 之于结构化数据。它提供了对存储的抽象。为您提供相同的编程模型,以便快速轻松地实现基于 REST 的内容服务。

    您可以像这样将它添加到您的项目中:

    pom.xml

    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>spring-content-mongo</artifactId>
        <version>0.12.0</version>    <!-- 1.0.0.M3 for Spring Boot 2.2 -->
    </dependency>
    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>spring-content-rest</artifactId>
        <version>0.12.0</version>    <!-- 1.0.0.M3 for Spring Boot 2.2 -->
    </dependency>
    

    确保您的应用程序上下文中存在 GridFsTemplate bean(图像将存储在 Mongo 的 GridFS 中)。 Mongo Storage 和 REST API 启用如下:

    @Configuration
    @EnableMongoStores
    @Import(org.springframework.content.rest.config.RestConfiguration.class) // Enable REST API
    public class MongoConfig extends AbstractMongoConfiguration {
    
       @Bean
       public GridFsTemplate gridFsTemplate() throws Exception {
          return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
       }
       ...
    

    要允许内容与您的用户实体相关联,请为其赋予以下属性:

    用户.java

    public class User {    
    
        @Id
        private String id;      
        //private Binary image;    replace this with -->
    
        @ContentId
        private String contentId;
    
        @ContentLength 
        private long contentLength = 0L;
    
        @MimeType
        private String mimeType;
    

    添加商店界面:

    UserImageStore.java

    public interface UserImageStore extends ContentStore<User, String> {
    }
    

    当您的应用程序启动时,Spring Content 将看到 Mongo/REST 模块的依赖关系,它会注入 UserImageStore 的 GridFS 实现,以及支持完整 CRUD 功能并将这些操作映射到UserImageStore 接口。 REST 端点将在/users 提供。

    curl -X PUT /users/{userId} -F "file=@/some/image.jpg" 将为用户userId 创建或更新用户图像

    curl -X GET /users/{userId} 将再次获取图像

    curl -X DELETE /users/{userId} 会删除图片

    正方体

    有了 Spring Content,你就可以使用它的事件处理机制来插入你的 tesseract OCR:

    @StoreEventHandler
    public static class OcrHandler {
    
       @Autowired
       private UserImageStore images;
    
       @HandleAfterSetContent
       @Order(Ordered.LOWEST_PRECEDENCE)
       public void handleAfterSetContent(User user) {
    
          tesseract.TessBaseAPI api = new tesseract.TessBaseAPI();
    
          // Initialize tesseract-ocr with English, without specifying tessdata path
          if (api.Init("/path/to/your/trained/data", "eng") != 0) {
              ...
          }
    
          byte[] bytes = new byte[0];
          try {
             // get the image from the user for ocr processing
             bytes = IOUtils.toByteArray(images.get(user));
          }
          catch (IOException e) {
             ...
          }
          lept.PIX pix = pixReadMem(bytes, bytes.length);
          api.SetImage(pix);
    
          BytePointer outText = api.GetUTF8Text();
    
          // use outText.getString() containing the ocr result
    
          api.End();
          outText.deallocate();
          pixDestroy(pix);
       }
    }
    

    有一些入门指南here。他们将 Spring Content 用于文件系统,但存储模块是可互换的。 Mongo 参考指南是here。有一个教程视频here。还有一个示例项目here

    HTH

    【讨论】:

    • 您好 Paul Warren,应用程序启动成功,并在点击发送时在 post man 表单数据中使用“localhost:8080/users/vijay”和图像文件,结果显示为 404 not found 错误。我添加了 jar 和依赖项,如 spring-content-mongo、spring-content-rest、content-store-api 一切都正确但邮递员不接受 url。它是否在应用程序属性中没有提到任何数据库的情况下被接受,我们没有使用任何 @Restcontroller用于上传和检索图像。并且 ocr 控制器也在 tesseract 中显示错误,它不接受依赖项。请指导我
    • 如果不仔细观察就很难分辨。您不需要创建任何控制器,这一切都为您完成。听起来有些豆子没有被注册。也不需要数据库。应该使用gridfs。 tesseract 事件处理程序只是一个示例。但是如果您可以通过一个小项目重现该问题,请将其推送到您在 github 中的组织,然后在 github 问题中将其引用到 spring-content。
    • 几个简单的检查:邮递员;上传是分段上传吗?网址; vijay 真的是 userId 吗?
    猜你喜欢
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2020-06-17
    • 2016-02-08
    • 1970-01-01
    • 2012-11-10
    相关资源
    最近更新 更多