-
Notifications
You must be signed in to change notification settings - Fork 4
/
fgosccnt.py
executable file
·3186 lines (2876 loc) · 118 KB
/
fgosccnt.py
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import sys
import re
import argparse
from pathlib import Path
from collections import Counter
import csv
from enum import Enum
import itertools
import json
from operator import itemgetter
import math
import datetime
import logging
from typing import Tuple, Union
import io
import cv2
from numpy import ndarray
import numpy as np
import pytesseract
from PIL import Image
from PIL.ExifTags import TAGS
import pageinfo
PROGNAME = "FGOスクショカウント"
VERSION = "0.4.0"
DEFAULT_ITEM_LANG = "jpn" # "jpn": japanese, "eng": English
logger = logging.getLogger(__name__)
class CustomAdapter(logging.LoggerAdapter):
"""
この adapter を通した場合、自動的にログ出力文字列の先頭に [target] が挿入される。
target は adapter インスタンス生成時に確定させること。
"""
def process(self, msg, kwargs):
return f"[{self.extra['target']}] {msg}", kwargs
class Ordering(Enum):
"""
ファイルの処理順序を示す定数
"""
NOTSPECIFIED = 'notspecified' # 指定なし
FILENAME = 'filename' # ファイル名
TIMESTAMP = 'timestamp' # 作成日時
def __str__(self):
return str(self.value)
basedir = Path(__file__).resolve().parent
Item_dir = basedir / Path("item/equip/")
CE_dir = basedir / Path("item/ce/")
Point_dir = basedir / Path("item/point/")
train_item = basedir / Path("item.xml") # item stack & bonus
train_chest = basedir / Path("chest.xml") # drop_coount (Old UI)
train_dcnt = basedir / Path("dcnt.xml") # drop_coount (New UI)
train_card = basedir / Path("card.xml") # card name
drop_file = basedir / Path("fgoscdata/hash_drop.json")
eventquest_dir = basedir / Path("fgoscdata/data/json/")
items_img = basedir / Path("data/misc/items_img.png")
bunyan1_img = basedir / Path("data/misc/bunyan1.png")
hasher = cv2.img_hash.PHash_create()
FONTSIZE_UNDEFINED = -1
FONTSIZE_NORMAL = 0
FONTSIZE_SMALL = 1
FONTSIZE_TINY = 2
FONTSIZE_NEWSTYLE = 99
PRIORITY_CE = 9000
PRIORITY_POINT = 3000
PRIORITY_ITEM = 700
PRIORITY_GEM_MIN = 6094
PRIORITY_MAGIC_GEM_MIN = 6194
PRIORITY_SECRET_GEM_MIN = 6294
PRIORITY_PIECE_MIN = 5194
PRIORITY_REWARD_QP = 9012
ID_START = 9500000
ID_QP = 1
ID_FP = 4
ID_REWARD_QP = 5
ID_GEM_MIN = 6001
ID_GEM_MAX = 6007
ID_MAGIC_GEM_MIN = 6101
ID_MAGIC_GEM_MAX = 6107
ID_SECRET_GEM_MIN = 6201
ID_SECRET_GEM_MAX = 6207
ID_PIECE_MIN = 7001
ID_MONUMENT_MAX = 7107
ID_EXP_MIN = 9700100
ID_EXP_MAX = 9707500
ID_2ZORO_DICE = 94047708
ID_3ZORO_DICE = 94047709
ID_NORTH_AMERICA = 93000500
ID_SYURENJYO = 94006800
ID_SYURENJYO_TMP = 94066100
ID_EVNET = 94000000
ID_GREEN_TEA = 94074504
ID_YELLOW_TEA = 94074505
ID_RED_TEA = 94074506
ID_WEST_AMERICA_AREA = 93040104
TIMEOUT = 15
QP_UNKNOWN = -1
class FgosccntError(Exception):
pass
class GainedQPandDropMissMatchError(FgosccntError):
pass
with open(drop_file, encoding='UTF-8') as f:
drop_item = json.load(f)
# JSONファイルから各辞書を作成
item_name = {item["id"]: item["name"] for item in drop_item}
item_name_eng = {item["id"]: item["name_eng"] for item in drop_item
if "name_eng" in item.keys()}
item_shortname = {item["id"]: item["shortname"] for item in drop_item
if "shortname" in item.keys()}
item_dropPriority = {item["id"]: item["dropPriority"] for item in drop_item}
item_background = {item["id"]: item["background"] for item in drop_item
if "background" in item.keys()}
item_type = {item["id"]: item["type"] for item in drop_item}
dist_item = {item["phash_battle"]: item["id"] for item in drop_item
if item["type"] == "Item" and "phash_battle" in item.keys()}
dist_ce = {item["phash"]: item["id"] for item in drop_item
if item["type"] == "Craft Essence"}
dist_ce_narrow = {item["phash_narrow"]: item["id"] for item in drop_item
if item["type"] == "Craft Essence"}
dist_secret_gem = {item["id"]: item["phash_class"] for item in drop_item
if 6200 < item["id"] < 6208
and "phash_class" in item.keys()}
dist_magic_gem = {item["id"]: item["phash_class"] for item in drop_item
if 6100 < item["id"] < 6108 and "phash_class" in item.keys()}
dist_gem = {item["id"]: item["phash_class"] for item in drop_item
if 6000 < item["id"] < 6008 and "phash_class" in item.keys()}
dist_exp_rarity = {item["phash_rarity"]: item["id"] for item in drop_item
if item["type"] == "Exp. UP"
and "phash_rarity" in item.keys()}
dist_exp_rarity_sold = {item["phash_rarity_sold"]: item["id"] for item
in drop_item if item["type"] == "Exp. UP"
and "phash_rarity_sold" in item.keys()}
dist_exp_rarity.update(dist_exp_rarity_sold)
dist_exp_rarity["1fe03fe0517fa0bf"] = 9701200 # fix #368
dist_exp_class = {item["phash_class"]: item["id"] for item in drop_item
if item["type"] == "Exp. UP"
and "phash_class" in item.keys()}
dist_exp_class_sold = {item["phash_class_sold"]: item["id"]
for item in drop_item
if item["type"] == "Exp. UP" and "phash_class_sold"
in item.keys()}
dist_exp_class.update(dist_exp_class_sold)
dist_point = {item["phash_battle"]: item["id"]
for item in drop_item
if item["type"] == "Point" and "phash_battle" in item.keys()}
with open(drop_file, encoding='UTF-8') as f:
drop_item = json.load(f)
freequest = []
evnetfiles = eventquest_dir.glob('**/*.json')
for evnetfile in evnetfiles:
try:
with open(evnetfile, encoding='UTF-8') as f:
event = json.load(f)
freequest = freequest + event
except (OSError, UnicodeEncodeError) as e:
logger.exception(e)
npz = np.load(basedir / Path('background.npz'))
hist_zero = npz["hist_zero"]
hist_gold = npz["hist_gold"]
hist_silver = npz["hist_silver"]
hist_bronze = npz["hist_bronze"]
def has_intersect(a, b):
"""
二つの矩形の当たり判定
隣接するのはOKとする
"""
return max(a[0], b[0]) < min(a[2], b[2]) \
and max(a[1], b[1]) < min(a[3], b[3])
class State():
def set_screen(self):
self.screen_type = "normal"
def set_char_position(self):
logger.debug("JP Standard Position")
def set_font_size(self):
logger.debug("JP Standard Font Size")
def set_max_qp(self):
self.max_qp = 999999999
logger.debug("999,999,999")
class JpNov2020(State):
def set_screen(self):
self.screen_type = "wide"
class JpAug2021(JpNov2020):
def set_font_size(self):
logger.debug("JP New Font Size")
def set_max_qp(self):
self.max_qp = 2000000000
logger.debug("2,000,000,000")
class NaState(State):
def set_char_position(self):
logger.debug("NA Standard Position")
class NaOct2022(NaState):
def set_screen(self):
self.screen_type = "wide"
def set_max_qp(self):
self.max_qp = 2000000000
logger.debug("2,000,000,000")
class Context:
def __init__(self):
self.jp_aug_2021 = JpAug2021()
self.jp_nov_2020 = JpNov2020()
self.jp = State()
self.na = NaState()
self.na_oct2022 = NaOct2022()
self.state = self.jp_aug_2021
self.set_screen()
self.set_font_size()
self.set_char_position()
self.set_max_qp()
def change_state(self, mode):
if mode == "jp":
self.state = self.jp_aug_2021
elif mode == "na":
self.state = self.na_oct2022
else:
raise ValueError("change_state method must be in {}".format(["jp", "na"]))
self.set_screen()
self.set_font_size()
self.set_char_position()
self.set_max_qp()
def set_screen(self):
self.state.set_screen()
def set_char_position(self):
self.state.set_char_position()
def set_font_size(self):
self.state.set_font_size()
def set_max_qp(self):
self.state.set_max_qp()
def get_coodinates(img: ndarray,
display: bool = False) -> Tuple[Tuple[int, int],
Tuple[int, int]]:
threshold: int = 30
height, width = img.shape[:2]
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if display:
cv2.imshow('image', img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
_, inv = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY_INV)
if display:
cv2.imshow('image', inv)
cv2.waitKey(0)
cv2.destroyAllWindows()
contours, _ = cv2.findContours(inv, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
contours2 = []
for cnt in contours:
_, _, w, h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
if 1.81 < w/h < 1.83 and area > height / 2 * width / 2 and height/h > 1080/910:
contours2.append(cnt)
if len(contours2) == 0:
raise ValueError("Game screen not found.")
max_contour = max(contours2, key=lambda x: cv2.contourArea(x))
x, y, width, height = cv2.boundingRect(max_contour)
return ((x, y), (x + width, y + height))
def standardize_size(frame_img: ndarray,
display: bool = False) -> Tuple[ndarray, float]:
TRAINING_WIDTH: int = 1754
height, width = frame_img.shape[:2]
if display:
pass
logger.debug("height: %d", height)
logger.debug("width: %d", width)
_, width, _ = frame_img.shape
resize_scale: float = TRAINING_WIDTH / width
logger.debug("resize_scale: %f", resize_scale)
if resize_scale > 1:
frame_img = cv2.resize(frame_img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_CUBIC)
elif resize_scale < 1:
frame_img = cv2.resize(frame_img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_AREA)
if display:
cv2.imshow('image', frame_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return frame_img, resize_scale
def area_decision(frame_img: ndarray,
display: bool = False) -> str:
"""
FGOアプリの地域を選択
"na", 'jp'に対応
'items_img.png' とのオブジェクトマッチングで判定
"""
img = frame_img[0:100, 0:500]
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if display:
cv2.imshow('image', img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
template = imread(items_img, 0)
res = cv2.matchTemplate(
img_gray,
template,
cv2.TM_CCOEFF_NORMED
)
threshold = 0.9
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
return "na"
return 'jp'
def check_page_mismatch(page_items: int, chestnum: int, pagenum: int, pages: int, lines: int) -> bool:
if pages == 1:
if chestnum + 1 != page_items:
return False
return True
if not (pages - 1) * 21 <= chestnum <= pages * 21 - 1:
return False
if pagenum == pages:
item_count = chestnum - ((pages - 1) * 21 - 1) + (pages * 3 - lines) * 7
if item_count != page_items:
return False
return True
class ScreenShot:
"""
戦利品スクリーンショットを表すクラス
"""
def __init__(self, args, img_rgb, svm, svm_chest, svm_dcnt, svm_card,
fileextention, exLogger, reward_only=False):
self.exLogger = exLogger
threshold = 80
self.img_rgb_orig = img_rgb
img_blue, img_green, img_red = cv2.split(img_rgb)
if (img_blue==img_green).all() & (img_green==img_red ).all():
raise ValueError("Input image is grayscale")
self.img_gray_orig = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
self.img_hsv_orig = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2HSV)
_, self.img_th_orig = cv2.threshold(self.img_gray_orig,
threshold, 255, cv2.THRESH_BINARY)
((self.x1, self.y1), (self.x2, self.y2)) = get_coodinates(self.img_rgb_orig)
# Remove the extra notch by centering
center = int((self.x2 - self.x1)/2 + self.x1)
half_width = min(center, img_rgb.shape[1] - center)
img_rgb_tmp = img_rgb[:, center - half_width:center + half_width]
try:
self.pagenum, self.pages, self.lines = pageinfo.guess_pageinfo(img_rgb_tmp)
if self.lines / self.pages > 3:
logger.warning("The maximum number of lines has been exceeded")
self.lines = self.pages * 3
except pageinfo.TooManyAreasDetectedError:
self.pagenum, self.pages, self.lines = (-1, -1, -1)
frame_img: ndarray = self.img_rgb_orig[self.y1: self.y2, self.x1: self.x2]
img_resize, resize_scale = standardize_size(frame_img)
self.img_rgb = img_resize
mode = area_decision(img_resize)
logger.debug("lang: %s", mode)
# UI modeを決める
sc = Context()
sc.change_state(mode)
self.max_qp = sc.state.max_qp
self.screen_type = sc.state.screen_type
dcnt_old, dcnt_new = self.drop_count_area(self.img_rgb_orig, resize_scale, sc)
if logger.isEnabledFor(logging.DEBUG):
cv2.imwrite('frame_img.png', img_resize)
if logger.isEnabledFor(logging.DEBUG):
if self.screen_type == "normal":
cv2.imwrite('dcnt_old.png', dcnt_old)
cv2.imwrite('dcnt_new.png', dcnt_new)
self.img_gray = cv2.cvtColor(self.img_rgb, cv2.COLOR_BGR2GRAY)
_, self.img_th = cv2.threshold(self.img_gray,
threshold, 255, cv2.THRESH_BINARY)
self.svm = svm
self.svm_chest = svm_chest
self.svm_dcnt = svm_dcnt
self.height, self.width = self.img_rgb.shape[:2]
if self.screen_type == "normal":
self.chestnum = self.ocr_tresurechest(dcnt_old)
if self.chestnum == -1:
self.chestnum = self.ocr_dcnt(dcnt_new)
else:
self.chestnum = self.ocr_dcnt(dcnt_new)
self.asr_y, self.actual_height = self.detect_scroll_bar()
logger.debug("Total Drop (OCR): %d", self.chestnum)
item_pts = self.img2points(mode)
logger.debug("item_pts:%s", item_pts)
self.items = []
self.current_dropPriority = PRIORITY_REWARD_QP
if reward_only:
# qpsplit.py で利用
item_pts = item_pts[0:1]
prev_item = None
# まんわか用イベント判定
template1 = cv2.imread(str(bunyan1_img), 0)
item15th = self.img_gray[item_pts[15][1]:item_pts[15][3], item_pts[15][0]:item_pts[15][2]]
res = cv2.matchTemplate(item15th, template1, cv2.TM_CCOEFF_NORMED)
threshold = 0.80
loc = np.where(res >= threshold)
self.Bunyan = False
for pt in zip(*loc[::-1]):
self.Bunyan = True
break
for i, pt in enumerate(item_pts):
if self.Bunyan and i == 14:
break
lx, _ = self.find_edge(self.img_th[pt[1]: pt[3],
pt[0]: pt[2]], reverse=True)
logger.debug("lx: %d", lx)
item_img_th = self.img_th[pt[1] + 37: pt[3] - 60,
pt[0] + lx: pt[2] + lx]
if self.is_empty_box(item_img_th):
break
item_img_rgb = self.img_rgb[pt[1]: pt[3],
pt[0] + lx: pt[2] + lx]
item_img_gray = self.img_gray[pt[1]: pt[3],
pt[0] + lx: pt[2] + lx]
if logger.isEnabledFor(logging.DEBUG):
cv2.imwrite('item' + str(i) + '.png', item_img_rgb)
dropitem = Item(args, i, prev_item, item_img_rgb, item_img_gray,
svm, svm_card, fileextention,
self.current_dropPriority, self.exLogger, mode)
if dropitem.id == -1:
break
self.current_dropPriority = item_dropPriority[dropitem.id]
if dropitem.id in [94069601, 94069602, 94069603]:
# まんわかイベントのバニヤンに隠されているドロップが問題を生じるので補正
dropitem.dropnum = 'x3'
self.items.append(dropitem)
prev_item = dropitem
if self.Bunyan:
lx, _ = self.find_edge(self.img_th[item_pts[14][1]: item_pts[14][3],
item_pts[14][0]: item_pts[14][2]], reverse=True)
item_img_rgb = self.img_rgb[item_pts[14][1]: item_pts[14][3],
item_pts[14][0] + lx: item_pts[14][2] + lx]
item_img_gray = self.img_gray[item_pts[14][1]: item_pts[14][3],
item_pts[14][0] + lx: item_pts[14][2] + lx]
dropitem = Item(args, i, prev_item, item_img_rgb, item_img_gray,
svm, svm_card, fileextention,
self.current_dropPriority, self.exLogger, mode)
self.items.append(dropitem)
self.itemlist = self.makeitemlist()
try:
self.total_qp = self.get_qp(mode)
self.qp_gained = self.get_qp_gained(mode)
except Exception as e:
self.total_qp = -1
self.qp_gained = -1
self.exLogger.warning("QP detection fails")
logger.exception(e)
if self.qp_gained > 0 and len(self.itemlist) == 0:
raise GainedQPandDropMissMatchError
logger.debug(f'pagenum(pageninfo) pagenum: {self.pagenum}, pages: {self.pages}, lines: {self.lines}')
self.pagenum, self.pages, self.lines = self.correct_pageinfo()
logger.debug(f'pagenum(coreected) pagenum: {self.pagenum}, pages: {self.pages}, lines: {self.lines}')
if not reward_only:
self.check_page_mismatch()
def check_page_mismatch(self):
if self.Bunyan:
num_items = len(self.itemlist) -1
else:
num_items = len(self.itemlist)
valid = check_page_mismatch(
num_items,
self.chestnum,
self.pagenum,
self.pages,
self.lines,
)
if not valid:
self.exLogger.warning("drops_count is a mismatch:")
self.exLogger.warning("drops_count = %d", self.chestnum)
self.exLogger.warning("drops_found = %d", len(self.itemlist))
def find_notch(self):
"""
直線検出で検出されなかったフチ幅を検出
"""
edge_width = 200
height, width = self.img_hsv_orig.shape[:2]
target_color = 0
for lx in range(edge_width):
img_hsv_x = self.img_hsv_orig[:, lx: lx + 1]
# ヒストグラムを計算
hist = cv2.calcHist([img_hsv_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, maxVal, _, maxLoc = cv2.minMaxLoc(hist)
if not (maxLoc[1] == target_color and maxVal > height * 0.7):
break
for rx in range(edge_width):
img_hsv_x = self.img_hsv_orig[:, width - rx - 1: width - rx]
# ヒストグラムを計算
hist = cv2.calcHist([img_hsv_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, maxVal, _, maxLoc = cv2.minMaxLoc(hist)
if not (maxLoc[1] == target_color and maxVal > height * 0.7):
break
return lx, rx
def drop_count_area(self, img: ndarray,
resize_scale,
sc,
display: bool = False) -> Tuple[Union[ndarray, None], ndarray]:
# widescreenかどうかで挙動を変える
if resize_scale > 1:
img = cv2.resize(img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_CUBIC)
elif resize_scale < 1:
img = cv2.resize(img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_AREA)
# ((x1, y1), (_, _)) = get_coodinates(img)
# 相対座標(旧UI)
dcnt_old = None
if sc.state.screen_type == "normal":
dcnt_old = img[int(self.y1*resize_scale) - 81: int(self.y1*resize_scale) - 44,
int(self.x1*resize_scale) + 1446: int(self.x1*resize_scale) + 1505]
if display:
cv2.imshow('image', dcnt_old)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 相対座標(新UI)
lx, rx = self.find_notch()
height, width = img.shape[:2]
if (width - lx - rx)/height > 16/8.96: # Issue #317
# Widescreen
dcnt_new = img[int(self.y1*resize_scale) - 20: int(self.y1*resize_scale) + 13,
width - 495 - rx: width - 415 - int(rx*resize_scale)]
else:
dcnt_new = img[int(self.y1*resize_scale) - 20: int(self.y1*resize_scale) + 13,
width - 430 : width - 340]
if display:
cv2.imshow('image', dcnt_new)
cv2.waitKey(0)
cv2.destroyAllWindows()
return dcnt_old, dcnt_new
def detect_scroll_bar(self):
'''
Modified from determine_scroll_position()
'''
width = self.img_rgb.shape[1]
topleft = (width - 90, 81)
bottomright = (width, 2 + 753)
if logger.isEnabledFor(logging.DEBUG):
img_copy = self.img_rgb.copy()
cv2.rectangle(img_copy, topleft, bottomright, (0, 0, 255), 3)
cv2.imwrite("./scroll_bar_selected2.jpg", img_copy)
gray_image = self.img_gray[
topleft[1]: bottomright[1],
topleft[0]: bottomright[0]
]
_, binary = cv2.threshold(gray_image, 200, 255, cv2.THRESH_BINARY)
if logger.isEnabledFor(logging.DEBUG):
cv2.imwrite("scroll_bar_binary2.png", binary)
contours = cv2.findContours(
binary,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE
)[0]
pts = []
for cnt in contours:
ret = cv2.boundingRect(cnt)
pt = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if ret[3] > 10:
pts.append(pt)
if len(pts) == 0:
logger.debug("Can't find scroll bar")
return -1, -1
elif len(pts) > 1:
max_cnt = max(contours, key=lambda x: cv2.contourArea(x))
ret = cv2.boundingRect(max_cnt)
pt = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if ret[3] <= 10:
logger.debug("Can't find scroll bar")
return -1, -1
return pt[1], pt[3] - pt[1]
def valid_pageinfo(self):
'''
Checking the content of pageinfo and correcting it when it fails
'''
if self.pagenum == -1 or self.pages == -1 or self.lines == -1:
return False
if (self.pagenum == 1 and self.pages == 1 and self.lines == 0) and self.chestnum > 20:
return False
elif self.itemlist[0]["id"] != ID_REWARD_QP and self.pagenum == 1:
return False
elif self.Bunyan and self.chestnum != -1 and self.pagenum != 1 \
and self.lines != int(self.chestnum/7) + 2:
return False
elif self.Bunyan is False and self.chestnum != -1 and self.pagenum != 1 \
and self.lines != int(self.chestnum/7) + 1:
return False
return True
def correct_pageinfo(self):
if self.valid_pageinfo() is False:
self.exLogger.warning("pageinfo validation failed")
if self.asr_y == -1 or self.actual_height == -1:
return 1, 1, 0
entire_height = 645
esr_y = 17
cap_height = 14 # 正規化後の im.height を 1155 であると仮定して計算した値
pagenum = pageinfo.guess_pagenum(self.asr_y, esr_y, self.actual_height, entire_height, cap_height)
pages = pageinfo.guess_pages(self.actual_height, entire_height, cap_height)
lines = pageinfo.guess_lines(self.actual_height, entire_height, cap_height)
return pagenum, pages, lines
else:
return self.pagenum, self.pages, self.lines
def calc_black_whiteArea(self, bw_image):
image_size = bw_image.size
whitePixels = cv2.countNonZero(bw_image)
whiteAreaRatio = (whitePixels / image_size) * 100 # [%]
return whiteAreaRatio
def is_empty_box(self, img_th):
"""
アイテムボックスにアイテムが無いことを判別する
"""
if self.calc_black_whiteArea(img_th) < 1:
return True
return False
def get_qp_from_text(self, text):
"""
capy-drop-parser から流用
"""
qp = 0
power = 1
# re matches left to right so reverse the list
# to process lower orders of magnitude first.
for match in re.findall("[0-9]+", text)[::-1]:
qp += int(match) * power
power *= 1000
return qp
def extract_text_from_image(self, image):
"""
capy-drop-parser から流用
"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, qp_image = cv2.threshold(gray, 65, 255, cv2.THRESH_BINARY_INV)
return pytesseract.image_to_string(
qp_image,
config="-l eng --oem 1 --psm 7 -c tessedit_char_whitelist=+,0123456789",
)
def get_qp(self, mode):
"""
capy-drop-parser から流用
tesseract-OCR is quite slow and changed to use SVM
"""
use_tesseract = False
pt = pageinfo.detect_qp_region(self.img_rgb_orig, mode)
logger.debug('pt from pageinfo: %s', pt)
if pt is None:
use_tesseract = True
qp_total = -1
if use_tesseract is False: # use SVM
im_th = cv2.bitwise_not(
self.img_th_orig[pt[0][1]: pt[1][1], pt[0][0]: pt[1][0]]
)
qp_total = self.ocr_text(im_th)
if use_tesseract or qp_total == -1:
if self.screen_type == "normal":
pt = ((288, 948), (838, 1024))
else:
pt = ((288, 838), (838, 914))
logger.debug('Use tesseract')
qp_total_text = self.extract_text_from_image(
self.img_rgb[pt[0][1]: pt[1][1], pt[0][0]: pt[1][0]]
)
logger.debug('qp_total_text from text: %s', qp_total_text)
qp_total = self.get_qp_from_text(qp_total_text)
logger.debug('qp_total from text: %s', qp_total)
if qp_total > self.max_qp:
self.exLogger.warning(
"qp_total exceeds the system's maximum: %s", qp_total
)
if qp_total == 0:
return QP_UNKNOWN
return qp_total
def get_qp_gained(self, mode):
use_tesseract = False
bounds = pageinfo.detect_qp_region(self.img_rgb_orig, mode)
if bounds is None:
# fall back on hardcoded bound
if self.screen_type == "normal":
bounds = ((398, 858), (948, 934))
else:
bounds = ((398, 748), (948, 824))
use_tesseract = True
else:
# Detecting the QP box with different shading is "easy", while detecting the absence of it
# for the gain QP amount is hard. However, the 2 values have the same font and thus roughly
# the same height (please NA...). You can consider them to be 2 same-sized boxes on top of
# each other.
(topleft, bottomright) = bounds
height = bottomright[1] - topleft[1]
topleft = (topleft[0], topleft[1] - height + int(height*0.12))
bottomright = (bottomright[0], bottomright[1] - height)
bounds = (topleft, bottomright)
logger.debug('Gained QP bounds: %s', bounds)
if logger.isEnabledFor(logging.DEBUG):
img_copy = self.img_rgb.copy()
cv2.rectangle(img_copy, bounds[0], bounds[1], (0, 0, 255), 3)
cv2.imwrite("./qp_gain_detection.jpg", img_copy)
qp_gain = -1
if use_tesseract is False:
im_th = cv2.bitwise_not(
self.img_th_orig[topleft[1]: bottomright[1],
topleft[0]: bottomright[0]]
)
qp_gain = self.ocr_text(im_th)
if use_tesseract or qp_gain == -1:
logger.debug('Use tesseract')
(topleft, bottomright) = bounds
qp_gain_text = self.extract_text_from_image(
self.img_rgb[topleft[1]: bottomright[1],
topleft[0]: bottomright[0]]
)
qp_gain = self.get_qp_from_text(qp_gain_text)
logger.debug('qp from text: %s', qp_gain)
if qp_gain == 0:
qp_gain = QP_UNKNOWN
return qp_gain
def find_edge(self, img_th, reverse=False):
"""
直線検出で検出されなかったフチ幅を検出
"""
edge_width = 4
_, width = img_th.shape[:2]
target_color = 255 if reverse else 0
for i in range(edge_width):
img_th_x = img_th[:, i:i + 1]
# ヒストグラムを計算
hist = cv2.calcHist([img_th_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, _, _, maxLoc = cv2.minMaxLoc(hist)
if maxLoc[1] == target_color:
break
lx = i
for j in range(edge_width):
img_th_x = img_th[:, width - j - 1: width - j]
# ヒストグラムを計算
hist = cv2.calcHist([img_th_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, _, _, maxLoc = cv2.minMaxLoc(hist)
if maxLoc[1] == 0:
break
rx = j
return lx, rx
def makeitemlist(self):
"""
アイテムを出力
"""
itemlist = []
for item in self.items:
tmp = {}
tmp['id'] = item.id
tmp['name'] = item.name
tmp['dropPriority'] = item_dropPriority[item.id]
tmp['dropnum'] = int(item.dropnum[1:])
tmp['bonus'] = item.bonus
tmp['category'] = item.category
itemlist.append(tmp)
return itemlist
def ocr_text(self, im_th):
h, w = im_th.shape[:2]
# 物体検出
im_th = cv2.bitwise_not(im_th)
contours = cv2.findContours(im_th,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[0]
item_pts = []
for cnt in contours:
ret = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
pt = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if ret[2] < int(w/2) and area > 80 and ret[1] < h/2 \
and 0.3 < ret[2]/ret[3] < 0.85 and ret[3] > h * 0.45:
flag = False
for p in item_pts:
if has_intersect(p, pt):
# どちらかを消す
p_area = (p[2]-p[0])*(p[3]-p[1])
pt_area = ret[2]*ret[3]
if p_area < pt_area:
item_pts.remove(p)
else:
flag = True
if flag is False:
item_pts.append(pt)
if len(item_pts) == 0:
# Recognizing Failure
return -1
item_pts.sort()
if len(item_pts) > len(str(self.max_qp)):
# QP may be misrecognizing the 10th digit or more, so cut it
item_pts = item_pts[len(item_pts) - len(str(self.max_qp)):]
logger.debug("ocr item_pts: %s", item_pts)
logger.debug("ドロップ桁数(OCR): %d", len(item_pts))
# Hog特徴のパラメータ
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
res = ""
for pt in item_pts:
test = []
if pt[0] == 0:
tmpimg = im_th[pt[1]:pt[3], pt[0]:pt[2]+1]
else:
tmpimg = im_th[pt[1]:pt[3], pt[0]-1:pt[2]+1]
tmpimg = cv2.resize(tmpimg, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size,
block_stride, cell_size, bins)
test.append(hog.compute(tmpimg)) # 特徴量の格納
test = np.array(test)
pred = self.svm_chest.predict(test)
res = res + str(int(pred[1][0][0]))
return int(res)
def ocr_tresurechest(self, drop_count_img):
"""
宝箱数をOCRする関数
"""
threshold = 80
img_gray = cv2.cvtColor(drop_count_img, cv2.COLOR_BGR2GRAY)
_, img_num = cv2.threshold(img_gray,
threshold, 255, cv2.THRESH_BINARY)
im_th = cv2.bitwise_not(img_num)
h, w = im_th.shape[:2]
# 情報ウィンドウが数字とかぶった部分を除去する
for y in range(h):
im_th[y, 0] = 255
for x in range(w): # ドロップ数7のときバグる対策 #54
im_th[0, x] = 255
return self.ocr_text(im_th)
def pred_dcnt(self, img):
"""
for JP new UI
"""
# Hog特徴のパラメータ
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
char = []
tmpimg = cv2.resize(img, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size,
block_stride, cell_size, bins)
char.append(hog.compute(tmpimg)) # 特徴量の格納
char = np.array(char)
pred = self.svm_dcnt.predict(char)
res = str(int(pred[1][0][0]))
return int(res)
def img2num(self, img, img_th, pts, char_w, end):
"""実際より小さく切り抜かれた数字画像を補正して認識させる
"""
height, width = img.shape[:2]
c_center = int(pts[0] + (pts[2] - pts[0])/2)
# newimg = img[:, item_pts[-1][0]-1:item_pts[-1][2]+1]
newimg = img[:, max(int(c_center - char_w/2), 0):min(int(c_center + char_w/2), width)]
threshold2 = 10
ret, newimg_th = cv2.threshold(newimg,
threshold2,
255,
cv2.THRESH_BINARY)
# 上部はもとのやつを上書き
# for w in range(item_pts[-1][2] - item_pts[-1][0] + 2):
for w in range(min(int(c_center + char_w/2), width) - max(int(c_center - char_w/2), 0)):
for h in range(end):
newimg_th[h, w] = img_th[h, w + int(c_center - char_w/2)]
# newimg_th[h, w] = img_th[h, w + item_pts[-1][0]]
newimg_th[height - 1, w] = 0
newimg_th[height - 2, w] = 0
newimg_th[height - 3, w] = 0
res = self.pred_dcnt(newimg_th)
return res
def ocr_dcnt(self, drop_count_img):
"""
ocr drop_count (for New UI)
"""
char_w = 28
threshold = 80
kernel = np.ones((4, 4), np.uint8)
img = cv2.cvtColor(drop_count_img, cv2.COLOR_BGR2GRAY)
_, img_th = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
img_th = cv2.dilate(img_th, kernel, iterations=1)
height, width = img_th.shape[:2]
end = -1
for i in range(height):