File size: 10,907 Bytes
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
17f5b5c
37d46fe
 
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37d46fe
17f5b5c
 
 
9efa605
17f5b5c
 
 
a1d4680
37d46fe
a1d4680
37d46fe
17f5b5c
37d46fe
 
 
 
 
 
 
 
 
 
 
 
 
17f5b5c
 
37d46fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17f5b5c
 
a1d4680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273

#include <iostream>
#include <sstream>
#include <regex>

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/imgproc.hpp>

#include "nlohmann/json.hpp"

#include "WeChatOcrResult.h"
#include "Utilities.h"

#include "utf8.h"

// 解析JSON响应
WeChatOcrResult* ParseOcrResult::ParseJson(const std::string& jsonResponseStr) {
    try {
        // 使用 nlohmann/json 解析 JSON 字符串
        auto ocrResponse = ocr_protobuf::OcrResponse();
        ocrResponse.ParseFromString(jsonResponseStr);
        
        // 创建结果对象
        WeChatOcrResult* result = new WeChatOcrResult();
        result->TaskId = ocrResponse.task_id();
        result->OcrResult = std::make_shared<OcrResult>();
        
        // 解析 OCR 结果
        if (ocrResponse.has_ocr_result()) {
            const auto& protoOcrResult = ocrResponse.ocr_result();
            
            // 解析单行结果
            for (int i = 0; i < protoOcrResult.single_result_size(); i++) {
                const auto& protoSingleResult = protoOcrResult.single_result(i);
                SingleResult singleResult;
                
                // 解析单行文本
                if (!protoSingleResult.single_str_utf8().empty()) {
                    singleResult.SingleStrUtf8 = Utilities::Base64Decode(protoSingleResult.single_str_utf8());
                }
                
                // 解析单行位置信息
                singleResult.SingleRate = protoSingleResult.single_rate();
                singleResult.Left = protoSingleResult.left();
                singleResult.Top = protoSingleResult.top();
                singleResult.Right = protoSingleResult.right();
                singleResult.Bottom = protoSingleResult.bottom();
                
                // 解析单行位置
                if (protoSingleResult.has_single_pos()) {
                    singleResult.SinglePos = std::make_shared<SinglePos>();
                    const auto& protoSinglePos = protoSingleResult.single_pos();
                    
                    for (int j = 0; j < protoSinglePos.pos_size(); j++) {
                        const auto& protoPosXY = protoSinglePos.pos(j);
                        Pos pos;
                        pos.X = protoPosXY.x();
                        pos.Y = protoPosXY.y();
                        singleResult.SinglePos->Pos.push_back(pos);
                    }
                }
                
                // 解析单字结果
                for (int j = 0; j < protoSingleResult.one_result_size(); j++) {
                    const auto& protoOneResult = protoSingleResult.one_result(j);
                    OneResult oneResult;
                    
                    // 解析单字文本
                    if (!protoOneResult.one_str_utf8().empty()) {
                        oneResult.OneStrUtf8 = Utilities::Base64Decode(protoOneResult.one_str_utf8());
                    }
                    
                    // 解析单字位置
                    if (protoOneResult.has_one_pos()) {
                        oneResult.OnePos = std::make_shared<OnePos>();
                        const auto& protoOnePos = protoOneResult.one_pos();
                        
                        for (int k = 0; k < protoOnePos.pos_size(); k++) {
                            const auto& protoPosXY = protoOnePos.pos(k);
                            Pos pos;
                            pos.X = protoPosXY.x();
                            pos.Y = protoPosXY.y();
                            oneResult.OnePos->Pos.push_back(pos);
                        }
                    }
                    
                    singleResult.OneResult.push_back(oneResult);
                }
                
                result->OcrResult->SingleResult.push_back(singleResult);
            }
        }
        
        return result;
    }
    catch (const std::exception& ex) {
        std::cerr << "Error parsing OCR result: " << ex.what() << std::endl;
        return nullptr;
    }
}

// 将SingleResult转换为JSON字符串
std::string OcrResult::ToJson(std::string& pth_img) const {

    cv::Mat mt = cv::imread(pth_img, cv::ImreadModes::IMREAD_COLOR_BGR);
	int width_img = mt.cols;
	int height_img = mt.rows;
    //cv::imshow("orig", mt);
    //cv::waitKey(0);

    nlohmann::ordered_json root;

    root["width"] =  width_img;
    root["height"] = height_img;

    nlohmann::ordered_json jsonResult = nlohmann::ordered_json::array();
    
    for (const auto& singleResult : SingleResult) {
        nlohmann::ordered_json jsonSingleResult;
        
        // 添加文本和评分信息
        jsonSingleResult["word"] = singleResult.SingleStrUtf8;  // 一行文本
        jsonSingleResult["prob"] = singleResult.SingleRate;

        int lft = (int)(singleResult.Left + 0.5);
        int tp = (int)(singleResult.Top + 0.5);
		int rht = (int)(singleResult.Right + 0.5);
		int btm = (int)(singleResult.Bottom + 0.5);
		int w = rht - lft;
		int h = btm - tp;

        lft = lft > width_img ? width_img : lft;
        tp = tp > height_img ? height_img : tp;
        rht = rht > width_img ? width_img : rht;
        btm = btm > height_img ? height_img : btm;
        w = w > width_img ? width_img : w;
        h = h > height_img ? height_img : h;

		jsonSingleResult["x"] = lft;
        jsonSingleResult["y"] = tp;
		jsonSingleResult["width"] = w;
        jsonSingleResult["height"] = h;

        nlohmann::json pos = nlohmann::json::array();
        pos.push_back({ {"x", lft}, {"y",  tp} });    // 左上
        pos.push_back({ {"x", rht}, {"y",  tp} });    // 右上
		pos.push_back({ {"x", rht}, {"y", btm } });   // 右下
		pos.push_back({ {"x", lft }, {"y", btm } });  // 左下

        jsonSingleResult["pos"] = pos;

        //cv::Mat tmt = mt.clone();
        //cv::rectangle(tmt, cv::Rect(lft, tp, w, h), cv::Scalar(0, 0, 255));
        //cv::imshow("line", tmt);
        //cv::waitKey(0);

        // 添加位置信息
        if (singleResult.SinglePos) {
            nlohmann::json posArray = nlohmann::json::array();
            for (const auto& pos : singleResult.SinglePos->Pos) {
                posArray.push_back({
                    {"x", pos.X},
                    {"y", pos.Y}
                });
            }
            //jsonSingleResult["position"] = posArray;  // 和前面的结果有一点点差异,但是很小。可以不要它
        }
        
        // 添加单字结果
        if (!singleResult.OneResult.empty()) {
            nlohmann::json oneResultArray = nlohmann::json::array();

            for (int i = 0; i < singleResult.OneResult.size(); i++) {

                const auto& oneResult = singleResult.OneResult[i];
                nlohmann::ordered_json jsonOneResult;

                if (oneResult.OneStrUtf8.empty()) {  // || std::regex_match(oneResult.OneStrUtf8, std::regex("^[\\s]+$")) 
                    continue;
                }

                // 虽说是单字结果,但是有可能是一个单词的多个字。这种情况拆出每一个字符,让它们在图片中有相同的坐标和宽高。既是整个单词的大框
                for (size_t j = 0; j < oneResult.OneStrUtf8.size();) {
                    size_t len = utf8codepointcalcsize((const utf8_int8_t*)&oneResult.OneStrUtf8[j]); // 计算字符字节数
                    std::string word = oneResult.OneStrUtf8.substr(j, len);

                    jsonOneResult["word"] = word;  // 单个字文本

                    int one_x = -1, one_y = -1, one_w = -1, one_h = h;

                    if (oneResult.OnePos) {
                        nlohmann::json posArray = nlohmann::json::array();
                        for (const auto& pos : oneResult.OnePos->Pos) {  // 理论上应该是有四个角的坐标,但是 wechat ocr 实际上只给出了一个左上角的坐标
                            //posArray.push_back({ {"x", pos.X},{"y", pos.Y} });
                            one_x = pos.X;
                            one_y = pos.Y;
                            break;
                        }
                        //jsonOneResult["position"] = posArray;
                    }

                    if (i == singleResult.OneResult.size() - 1) {
                        one_w = rht - one_x;
                    }
                    else {
                        one_w = singleResult.OneResult[i + 1].OnePos->Pos[0].X - one_x;  // 获取下一个单字的左上角坐标
                    }

                    jsonOneResult["x"] = one_x;
                    jsonOneResult["y"] = one_y;
                    jsonOneResult["w"] = one_w;
                    jsonOneResult["h"] = one_h;

                    oneResultArray.push_back(jsonOneResult);

                    //cv::Mat tmt = mt.clone();
                    //cv::rectangle(tmt, cv::Rect(one_x, one_y, one_w, one_h), cv::Scalar(0, 0, 255));
                    //cv::imshow("line", tmt);
                    //cv::waitKey(0);

                    j += len;
                }


                //jsonOneResult["word"] = oneResult.OneStrUtf8;  // 单个字文本

				//int one_x = -1, one_y = -1, one_w = -1, one_h = h;
    //            
    //            if (oneResult.OnePos) {
    //                nlohmann::json posArray = nlohmann::json::array();
				//	for (const auto& pos : oneResult.OnePos->Pos) {  // 理论上应该是有四个角的坐标,但是 wechat ocr 实际上只给出了一个左上角的坐标
    //                    //posArray.push_back({ {"x", pos.X},{"y", pos.Y} });
    //                    one_x = pos.X;
    //                    one_y =  pos.Y;
    //                    break;
    //                }
    //                //jsonOneResult["position"] = posArray;
    //            }

    //            if (i == singleResult.OneResult.size() - 1) {
    //                one_w = rht - one_x;
    //            }
    //            else {
				//	one_w =  singleResult.OneResult[i + 1].OnePos->Pos[0].X - one_x;  // 获取下一个单字的左上角坐标
    //            }

    //            jsonOneResult["x"] = one_x;
    //            jsonOneResult["y"] = one_y;
    //            jsonOneResult["w"] = one_w;
    //            jsonOneResult["h"] = one_h;
    //            
    //            oneResultArray.push_back(jsonOneResult);


                //cv::Mat tmt = mt.clone();
                //cv::rectangle(tmt, cv::Rect(one_x, one_y, one_w, one_h), cv::Scalar(0, 0, 255));
                //cv::imshow("line", tmt);
                //cv::waitKey(0);

            }
            jsonSingleResult["charInfo"] = oneResultArray;
        }
        
        jsonResult.push_back(jsonSingleResult);
    }
    
    root["prism_wordsInfo"] = jsonResult;

    return root.dump(4);  // 使用4个空格的缩进来保留空白
}