-
Notifications
You must be signed in to change notification settings - Fork 9
/
qtvtt.py
13277 lines (10978 loc) · 570 KB
/
qtvtt.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 python
# -*- coding: iso-8859-1 -*-
"""
Qt Virtual Table Top
(c) Antonio Tejada 2022
References
- https://github.com/qt/qt5
- https://github.com/qt/qtbase/tree/5.3
"""
import csv
import io
import json
import logging
import math
import os
import random
import re
import SimpleHTTPServer
import SocketServer
import string
import StringIO
import sys
import tempfile
import thread
import time
import urllib
import zipfile
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import *
from PyQt5.QtMultimedia import *
try:
# new location for sip
# https://www.riverbankcomputing.com/static/Docs/PyQt5/incompatibilities.html#pyqt-v5-11
# XXX Untested
from PyQt5 import sip
except ImportError:
import sip
def enable_zip_remove(func):
# See
# https://stackoverflow.com/questions/4653768/overwriting-file-in-ziparchive
# Note that code causes "bad magic number for central directory" because of
# missing truncate
#
# A simpler way of doing this but that doesn't shrink the file is removing
# the entry from infofiles (central directory), since zip allows having
# orphan data in the file that is not part of the central directory. The
# file could be purged after the fact or keep them as version history since
# the local file headers keep filename and date. Safely retrieving local
# entries by scanning the zip is not guaranteed to work by the zip format in
# general, since implementations are free to write in the "gaps" not indexed
# by the central directory, but can it be guaranteed here since qvt files
# are QtVTT only.
#
# Yet another way is to create a new zip file and copy all members but for
# the one to remove
import functools
import operator
def _zipfile_remove_member(self, delete_member):
# get a sorted filelist by header offset, in case the dir order
# doesn't match the actual entry order
fp = self.fp
filelist = sorted(self.filelist, key=operator.attrgetter('header_offset'))
for i in range(len(filelist)):
info = filelist[i]
# find the target member
if (info.header_offset < delete_member.header_offset):
logger.info("Skipping %r at offset %d", info.filename, info.header_offset)
continue
# get the total size of the entry
entry_size = None
if i == len(filelist) - 1:
entry_size = self.start_dir - info.header_offset
else:
entry_size = filelist[i + 1].header_offset - info.header_offset
# found the member, set the entry offset
if (delete_member == info):
logger.info("Deleting %r at offset %d", info.filename, info.header_offset)
delete_entry_size = entry_size
continue
logger.info("Moving %r from offset %d to %d", info.filename, info.header_offset, info.header_offset - delete_entry_size)
# Move entry
# read the actual entry data
fp.seek(info.header_offset)
entry_data = fp.read(entry_size)
# update the header
info.header_offset -= delete_entry_size
# write the entry to the new position
fp.seek(info.header_offset)
fp.write(entry_data)
fp.flush()
# update state
self.start_dir -= delete_entry_size
self.filelist.remove(delete_member)
del self.NameToInfo[delete_member.filename]
self._didModify = True
# seek to the start of the central dir
fp.seek(self.start_dir)
# Truncate since it will probably have leftovers from the deleted file
# and zip requires the end of the file to contain only the central dir
fp.truncate()
def zipfile_remove(self, member):
"""Remove a file from the archive. The archive must be open with mode 'a'"""
if self.mode != 'a':
raise RuntimeError("remove() requires mode 'a'")
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
# Not in 2.7
if (False):
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists."
)
# Make sure we have an info object
if isinstance(member, zipfile.ZipInfo):
# 'member' is already an info object
zinfo = member
else:
# get the info object
zinfo = self.getinfo(member)
return self._zipfile_remove_member(zinfo)
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not hasattr(zipfile.ZipFile, "remove"):
setattr(zipfile.ZipFile, "_zipfile_remove_member", _zipfile_remove_member)
setattr(zipfile.ZipFile, "remove", zipfile_remove)
return func(*args, **kwargs)
return wrapper
class LineHandler(logging.StreamHandler):
"""
Split lines in multiple records, fill in %(className)s
"""
def __init__(self):
super(LineHandler, self).__init__()
def emit(self, record):
# Find out class name, _getframe is supposed to be faster than inspect,
# but less portable
# caller_locals = inspect.stack()[6][0].f_locals
caller_locals = sys._getframe(6).f_locals
clsname = ""
zelf = caller_locals.get("self", None)
if (zelf is not None):
clsname = class_name(zelf) + "."
zelf = None
caller_locals = None
# Indent all lines but the first one
indent = ""
text = record.getMessage()
messages = text.split('\n')
for message in messages:
r = record
r.msg = "%s%s" % (indent, message)
r.className = clsname
r.args = None
super(LineHandler, self).emit(r)
indent = " "
def setup_logger(logger):
"""
Setup the logger with a line break handler
"""
logging_format = "%(asctime).23s %(levelname)s:%(filename)s(%(lineno)d):[%(thread)d] %(className)s%(funcName)s: %(message)s"
logger_handler = LineHandler()
logger_handler.setFormatter(logging.Formatter(logging_format))
logger.addHandler(logger_handler)
return logger
logger = logging.getLogger(__name__)
setup_logger(logger)
logger.setLevel(logging.DEBUG)
#logger.setLevel(logging.WARNING)
#logger.setLevel(logging.INFO)
try:
import numpy as np
except:
logger.warning("numpy not installed, image filters disabled")
np = None
class Struct:
"""
A structure that can have any fields defined or added.
s = Struct(field0=value0, field1=Value1)
s.field2 = value2
or
s = Struct(**{field0 : value0, field1=value1})
"""
def __init__(self, **entries):
self.__dict__.update(entries)
class JSONStructEncoder(json.JSONEncoder):
"""
JSON Encoder for Structs
"""
def default(self, obj):
if (isinstance(obj, Struct)):
return obj.__dict__
else:
return json.JSONEncoder.default(self, obj)
def report_versions():
logger.info("Python version: %s", sys.version)
# Numpy is only needed to apply edge detection filters for automatic wall
# generation
np_version = "Not installed"
try:
import numpy as np
np_version = np.__version__
except:
logger.warning("numpy not installed, automatic wall generation disabled")
logger.info("Numpy version: %s", np_version)
logger.info("Qt version: %s", QT_VERSION_STR)
logger.info("PyQt version: %s", PYQT_VERSION_STR)
pyqt5_sqlite_version = "Not installed"
pyqt5_sqlite_compile_options = []
try:
from PyQt5.QtSql import QSqlDatabase
db = QSqlDatabase.addDatabase("QSQLITE")
db.open()
query = db.exec_("SELECT sqlite_version();")
query.first()
pyqt5_sqlite_version = query.value(0)
query = db.exec_("PRAGMA compile_options;")
while (query.next()):
pyqt5_sqlite_compile_options.append(query.value(0))
db.close()
except:
# On Linux QtSql import is known to fail when python-pyqt5.qtsql is not
# installed, needs
# apt install python-pyqt5.qtsql
pass
logger.info("QSQLITE version: %s", pyqt5_sqlite_version)
logger.info("QSQLITE compile options: %s", pyqt5_sqlite_compile_options)
logger.info("Qt plugin path: %s", os.environ.get("QT_PLUGIN_PATH", "Not set"))
logger.info("QCoreApplication.libraryPaths: %s", QCoreApplication.libraryPaths())
logger.info("QLibraryInfo.PrefixPath: %s", QLibraryInfo.location(QLibraryInfo.PrefixPath))
logger.info("QLibraryInfo.PluginsPath: %s", QLibraryInfo.location(QLibraryInfo.PluginsPath))
logger.info("QLibraryInfo.LibrariesPath: %s", QLibraryInfo.location(QLibraryInfo.LibrariesPath))
logger.info("QLibraryInfo.LibrarieExecutablesPath: %s", QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath))
logger.info("QLibraryInfo.BinariesPath: %s", QLibraryInfo.location(QLibraryInfo.BinariesPath))
def print_gc_stats(collect = True):
# XXX This takes multiple seconds eg when "x" cells in the the
# combattracker, disabled (probably due to innefficient setscene which
# calls addImage, review when scene update is piecemeal)
return
import gc
logger.info("GC stats")
logger.info("garbage %r", gc.garbage)
logger.info("gc counts %s", gc.get_count())
if (collect):
logger.info("gc collecting")
gc.collect()
logger.info("gc collected")
logger.info("garbage %r", gc.garbage)
logger.info("gc counts %s", gc.get_count())
def list_getat(l, i, default = None):
"""
Get list item at position i, or return default if list is empty, in a
similar manner to dict.get()
"""
return default if (len(l) == 0) else l[i]
def os_copy(src_filepath, dst_filepath):
logger.info("Copying from %r to %r", src_filepath, dst_filepath)
with open(src_filepath, "rb") as f_src, open(dst_filepath, "wb") as f_dst:
chunk_size = 4 * 2 ** 10
chunk = None
while (chunk != ""):
chunk = f_src.read(chunk_size)
f_dst.write(chunk)
def os_path_name(path):
"""
Return name from dir1/dir2/name.ext
"""
return os.path.splitext(os.path.basename(path))[0]
def os_path_ext(path):
"""
Return .ext from dir1/dir2/name.ext
"""
return os.path.splitext(path)[1]
def os_path_normall(path):
return os.path.normcase(os.path.normpath(path))
def os_path_isroot(path):
# Checking path == os.path.dirname(path) is the recommended way
# of checking for the root directory
# This works for both regular paths and SMB network shares
dirname = os.path.dirname(path)
return (path == dirname)
def os_path_abspath(path):
# The os.path library (split and the derivatives dirname, basename) slash
# terminates root directories, eg
# os.path.split("\\") ('\\', '')
# os.path.split("\\dir1") ('\\', 'dir1')
# os.path.split("\\dir1\\dir2") ('\\dir1', 'dir2')
# os.path.split("\\dir1\\dir2\\") ('\\dir1\\dir2', '')
# this includes SMB network shares, where the root is considered to be the
# pair \\host\share\ eg
# os.path.split("\\\\host\\share") ('\\\\host\\share', '')
# os.path.split("\\\\host\\share\\") ('\\\\host\\share\\', '')
# os.path.split("\\\\host\\share\\dir1") ('\\\\host\\share\\', 'dir1')
# abspath also slash terminates regular root directories,
# os.path.abspath("\\") 'C:\\'
# os.path.abspath("\\..") 'C:\\'
# unfortunately fails to slash terminate SMB network shares root
# directories, eg
# os.path.abspath("\\\\host\\share\\..") \\\\host\\share
# os.path.abspath("\\\\host\\share\\..\\..") '\\\\host\\share
# Without the trailing slash, functions like isabs fail, eg
# os.path.isabs("\\\\host\\share") False
# os.path.isabs("\\\\host\\share\\") True
# os.path.isabs("\\\\host\\share\\dir") True
# os.path.isabs("\\\\host\\share\\..") True
# See https://stackoverflow.com/questions/34599208/python-isabs-does-not-recognize-windows-unc-path-as-absolute-path
# This fixes that by making sure root directories are always slash
# terminated
abspath = os.path.abspath(os.path.expanduser(path))
if ((not abspath.endswith(os.sep)) and os_path_isroot(abspath)):
abspath += os.sep
logger.info("%r is %r", path, abspath)
return abspath
def index_of(l, item):
"""
Find the first occurrence of item in the list or return -1 if not found
"""
try:
return l.index(item)
except ValueError:
return -1
def find_parent(ancestor, item):
logger.info("Looking for %s in %s", item, ancestor)
if (isinstance(ancestor, (list, tuple))):
for value in ancestor:
if (value is item):
return ancestor
l = find_parent(value, item)
if (l is not None):
return l
elif (hasattr(ancestor, "__dict__")):
for value in ancestor.__dict__.values():
if (value is item):
return ancestor
l = find_parent(value, item)
if (l is not None):
return l
return None
def class_name(o):
return o.__class__.__name__
def math_norm(v):
return math.sqrt(v[0] ** 2 + v[1] ** 2)
def math_subtract(v, w):
return (v[0] - w[0], v[1] - w[1])
def math_dotprod(v, w):
return (v[0] * w[0] + v[1] * w[1])
def bytes_to_data_url(bytes):
import base64
base64_image = base64.b64encode(bytes).decode('utf-8')
# XXX This assumes it's a png (note that at least QTextEdit doesn't care and
# renders jpegs too even if declared as image/png)
data_url = 'data:image/png;base64,%s' % base64_image
return data_url
def qSizeToPointF(size):
return QPointF(size.width(), size.height())
def qSizeToPoint(size):
return QPoint(size.width(), size.height())
def qtuple(q):
"""
Convert Qt vectors (QPoint, etc) to tuples
"""
if (isinstance(q, (QPoint, QPointF, QVector2D))):
return (q.x(), q.y())
elif (isinstance(q, (QSize, QSizeF))):
return (q.width(), q.height())
elif (isinstance(q, (QLine, QLineF))):
return (qtuple(q.p1()), qtuple(q.p2()))
elif (isinstance(q, (QRect, QRectF))):
# Note this returns x,y,w,h to match Qt parameters
return (qtuple(q.topLeft()), qtuple(q.size()))
elif (isinstance(q, (QColor))):
return (q.red(), q.green(), q.blue())
else:
assert False, "Unhandled Qt type!!!"
def qlist(q):
return list(qtuple(q))
def qAngleSign(qv1, qv2):
# Return the sign of the cross product (z vector
# pointing up or down)
crossz = qv1.x() * qv2.y() - qv1.y() * qv2.x()
return 1 if (crossz > 0) else -1 if (crossz < 0) else 0
alignmentFlagToName = {
getattr(Qt, name) : name for name in vars(Qt)
if isinstance(getattr(Qt, name), Qt.AlignmentFlag)
}
def qAlignmentFlagToString(alignmentFlag):
return alignmentFlagToName.get(int(alignmentFlag), str(alignmentFlag))
fontWeightToName = {
getattr(QFont, name) : name for name in vars(QFont)
if isinstance(getattr(QFont, name), QFont.Weight)
}
def qFontWeightToString(fontWeight):
return fontWeightToName.get(int(fontWeight), str(fontWeight))
eventTypeToName = {
getattr(QEvent, name) : name for name in vars(QEvent)
if isinstance(getattr(QEvent, name), QEvent.Type)
}
def qEventTypeToString(eventType):
return eventTypeToName.get(eventType, str(eventType))
class EventTypeString:
"""
Using the class instead of the function directly, prevents the conversion to
string when used as logging parameter, increasing performance.
"""
def __init__(self, eventType):
self.eventType = eventType
def __str__(self):
return qEventTypeToString(self.eventType)
graphicsItemChangeToName = {
getattr(QGraphicsItem, name) : name for name in vars(QGraphicsItem)
if isinstance(getattr(QGraphicsItem, name), QGraphicsItem.GraphicsItemChange)
}
def qGraphicsItemChangeToString(change):
return graphicsItemChangeToName.get(change, str(change))
class GraphicsItemChangeString:
"""
Using the class instead of the function directly, prevents the conversion to
string when used as logging parameter, increasing performance.
This has been verified to be a win with high frequency functions like
itemChange/d
"""
def __init__(self, change):
self.change = change
def __str__(self):
return qGraphicsItemChangeToString(self.change)
def qYesNoCancelMessageBox(parent, title, message):
return QMessageBox.question(parent, title, message,
buttons=QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
# Set it explicitly. Despite what docs say, the default is Yes
defaultButton=QMessageBox.Cancel)
def qFindTabBarFromDockWidget(dock):
logger.info("%s", dock.windowTitle())
# QDockWidget tabs are QTabBars children of the main window, in C++ the dock
# can be found by checking that the QDockWidget address matches
# tab.tabData(), use sip to get the underlying C++ pointer and compare
dock_ptr = sip.unwrapinstance(dock)
for tabBar in dock.parent().findChildren(QTabBar):
i = 0
# There may be multiple tab buttons per tab bar, each activating a
# different QDockWidget
while (tabBar.tabData(i) is not None):
if (dock_ptr == tabBar.tabData(i)):
return tabBar
i += 1
return None
def qFindDockWidgetFromTabBar(tabBar, index):
logger.info("%s %d", tabBar.windowTitle(), index)
for dock in tabBar.parent().findChildren(QDockWidget):
# QDockWidget tabs are QTabBars children of the main window, in C++ the
# dock can be found by checking that the QDockWidget address matches
# tab.tabData(), use sip to get the underlying C++ pointer and compare
dock_ptr = sip.unwrapinstance(dock)
if (tabBar.tabData(index) == dock_ptr):
return dock
return None
def qLaunchWithPreferredAp(filepath):
# pyqt5 on lxde raspbian fails to invoke xdg-open for unknown reasons and
# falls back to invoking the web browser instead, use xdg-open explicitly on
# "xcb" platforms (X11)
# See https://github.com/qt/qtbase/blob/067b53864112c084587fa9a507eb4bde3d50a6e1/src/gui/platform/unix/qgenericunixservices.cpp#L129
if (QApplication.platformName() != "xcb"):
url = QUrl.fromLocalFile(filepath)
QDesktopServices.openUrl(url)
else:
# Note there's no splitCommand in this version of Qt5, build the
# argument list manually
QProcess.startDetached("xdg-open", [filepath])
def qImageToDataUrl(imageOrPixmap, imageFormat):
"""
This works for both QImage and QPixmap because both have the same save
member function
"""
ba = QByteArray()
buff = QBuffer(ba)
buff.open(QIODevice.WriteOnly)
ok = imageOrPixmap.save(buff, imageFormat)
assert ok
imgBytes = ba.data()
dataUrl = bytes_to_data_url(imgBytes)
return dataUrl
def qKeyEventToSequence(event):
assert (event.type() in [QEvent.KeyPress, QEvent.ShortcutOverride])
if (event.type() == QEvent.KeyPress):
# Use nativeVirtualKey so ctrl+shift+1 can be compared against
# "ctrl+shift+1" instead of "ctrl+shift+!", etc
key = event.nativeVirtualKey()
else:
key = event.key()
return QKeySequence(key | int(event.modifiers()))
def qEventIsShortcut(event, shortcut_or_list):
if (isinstance(shortcut_or_list, (list, tuple))):
return any([qEventIsShortcut(event, shortcut) for shortcut in shortcut_or_list])
else:
return (qKeyEventToSequence(event) == QKeySequence(shortcut_or_list))
def qEventIsKeyShortcut(event, shortcut_or_list):
if (event.type() == QEvent.KeyPress):
return qEventIsShortcut(event, shortcut_or_list)
else:
return False
def qEventIsShortcutOverride(event, shortcut_or_list):
if (event.type() == QEvent.ShortcutOverride):
return qEventIsShortcut(event, shortcut_or_list)
else:
return False
save_np_debug_images = False
def np_save(a, filepath):
# This can be called with 2D arrays that degenerate to a line, bring those
# back to 2D arrays
if (len(a.shape) == 1):
a = np.array([a])
h, w = a.shape[0:2]
bits = None
byte_stride = None
format = None
# Convert data type
if (a.dtype == 'bool'):
a = a * 255
elif (a.dtype in ['float32', 'float64']):
# Assumes range 0 to 1
a = a * 255.0
# Note astype copies by default
a = a.astype(np.uint8)
# Convert data dimensions
if ((len(a.shape) == 2) or (a.shape[2] == 1)):
# Expand one component to three
# XXX This version of qt has no grayscale8 or grayscale16, replicate to
# RGB8
a = np.repeat(a, 3).reshape((h, w, 3))
assert len(a.shape) == 3
assert a.shape[2] in [3, 4]
assert a.dtype == 'uint8'
format = QImage.Format_RGB888 if (a.shape[2] == 3) else QImage.Format_RGBA8888
image = QImage(a.data, w, h, a.shape[2] * w, format)
image.save(filepath)
def np_saveset(a, s, value, filepath):
# Note astype copies by default
b = a.astype(np.uint8)
if (len(s) > 0):
# For some reason b[np.array(list(s)).T] doesn't work (tries
# to use the arrays as if not transposed) it needs to be
# copied to intermediate arrays and then used as indices
j, i = np.array(list(s)).T
b[j, i] = value
np_save(b, filepath)
def np_pixmaptoarray(pixmap):
image = pixmap.toImage()
pixels = image.constBits().asstring(image.height() * image.bytesPerLine())
w = image.width()
h = image.height()
# XXX Needs to check line stride
# XXX Needs non-alpha support
a = np.fromstring(pixels, dtype=np.uint8).reshape((h, w, 4))
return a
def np_houghlines(a):
"""
XXX Not really tested
"""
def build_hough_space_fom_image(img, shape = (100, 300), val = 1):
hough_space = np.zeros(shape)
for i, row in enumerate(img):
for j, pixel in enumerate(row):
if pixel != val : continue
hough_space = add_to_hough_space_polar((i,j), hough_space)
return hough_space
def add_to_hough_space_polar(p, feature_space):
space = np.linspace(-np.pi/2.0, np.pi/2.0, len(feature_space))
d_max = len(feature_space[0]) / 2
for i in range(len(space)):
theta = space[i]
d = int(p[0] * np.sin(theta) + p[1] * np.cos(theta)) + d_max
if (d >= d_max * 2) : continue
feature_space[i, d] += 1
return feature_space
shape = (100, 2*int(math.ceil(np.sqrt(a.shape[0]**2 + a.shape[1]**2))))
hough = build_hough_space_fom_image(a, shape=shape, val=255)
# Get sorted indices, increasing values
idx = np.dstack(np.unravel_index(np.argsort(hough, axis=None), hough.shape))[0]
lines = []
for theta, r in idx[-20:]:
theta = theta * np.pi / hough.shape[0] - np.pi/2.0
r = r - hough.shape[1]/2.0
a = np.cos(theta)
b = np.sin(theta)
# x0 stores the value rcos(theta)
x0 = a*r
# y0 stores the value rsin(theta)
y0 = b*r
# x1 stores the rounded off value of (rcos(theta)-1000sin(theta))
x1 = int(x0 + shape[1]*(-b))
# y1 stores the rounded off value of (rsin(theta)+1000cos(theta))
y1 = int(y0 + shape[1]*(a))
# x2 stores the rounded off value of (rcos(theta)+1000sin(theta))
x2 = int(x0 - shape[1]*(-b))
# y2 stores the rounded off value of (rsin(theta)-1000cos(theta))
y2 = int(y0 - shape[1]*(a))
lines.append((x1, y1, x2, y2))
hough *= 255.0 / hough.max()
hough = hough.astype(np.uint8)
if (save_np_debug_images):
np_save(hough, os.path.join("_out", "hough.png"))
return lines
def np_filter(a, kernel):
"""
Convolve the kernel on the array
The convolution will skip the necessary rows and columns to prevent the
kernel sampling outside the image.
@param numeric or boolean 2D array
@param kernel numeric or boolean kernel, 2D square array
@return array resulting of convolving the kernel with the array
"""
logger.info("begin a %s kernel %s", a.shape, kernel.shape)
# This method 3secs vs. 2mins for the naive method
# See https://stackoverflow.com/questions/2448015/2d-convolution-using-python-and-numpy
# apply kernel to image, return image of the same shape, assume both image
# and kernel are 2D arrays
# optionally flip the kernel
## kernel = np.flipud(np.fliplr(kernel))
width = kernel.shape[0]
# fill the output array with zeros; do not use np.empty()
b = np.zeros(a.shape)
# crop the writes to the valid region (alternatively could pad the source)
# - For odd kernel sizes, this will skip the same number of leftmost and
# rightmost columns and topmost and bottomest rows
# - For even kernel sizes, this will skip an extra leftmost or topmost
# column/row
bb = b[width/2:b.shape[0]-(width-1)/2,width/2:b.shape[1]-(width-1)/2]
# shift the image around each pixel, multiply by the corresponding kernel
# value and accumulate the results
for j in xrange(width):
for i in xrange(width):
bb += a[j:j+a.shape[0]-width+1, i:i+a.shape[1]-width+1] * kernel[j, i]
# optionally clip values exceeding the limits
## np.clip(b, 0, 255, out=b)
logger.info("end")
return b
def np_naive_filter(a, kernel):
logger.info("begin a %s kernel %s", a.shape, kernel.shape)
kernel_diameter = kernel.shape[0]
# a = a[::4,::4]
#a = a[0:a.shape[0]/4, 0:a.shape[1]/4]
b = np.zeros(a.shape)
kernel = kernel.reshape(-1)
sum_kernel = sum(kernel)
kernel_diameter2 = kernel_diameter / 2
for j in xrange(0, a.shape[0] - kernel_diameter + 1):
for i in xrange(0, a.shape[1] - kernel_diameter + 1):
b[j + kernel_diameter2, i + kernel_diameter2] = (kernel.dot(a[j: j + kernel_diameter, i: i + kernel_diameter].flat) == sum_kernel) * 255
logger.info("end")
if (save_np_debug_images):
np_save(b, os.path.join("_out", "filter.png"))
return b
def np_erode(a, kernel_width):
"""
Apply an erosion operator to the 2D boolean array
@param a boolean 2D array
@param kernel_width width of the erosion kernel to use
@return boolean 2D array with True on the non eroded elements, False otherwise
"""
logger.info("a %s kernel %s", a.shape, kernel_width)
kernel = np.ones((kernel_width, kernel_width))
kernel_sum = sum(kernel.flat)
a = np_filter(a, kernel)
a = np.where(a == kernel_sum, True, False)
if (save_np_debug_images):
np_save(a, os.path.join("_out", "erode.png"))
return a
def np_graythreshold(a, threshold):
# Convert to grayscale
##logger.info("Grayscaling")
a = np.dot(a[...,:4], [0.2989, 0.5870, 0.1140, 0]).astype(np.uint8)
# Threshold
##logger.info("Thresholding")
# XXX This returns an iterator, not an array, change to np.where?
a = (a <= threshold)
if (save_np_debug_images):
logger.info("Saving threshold")
np_save(a, os.path.join("_out", "threshold.png"))
return a
def np_bisect_findmaxfiltersize(a, i, j, threshold):
"""
Find the largest nxn erode filter size that fits and contains the provided
array coordinate
@param a boolean array
@param x,y coordinates to start probing the filter size
@return int with max filter size
"""
logger.info("i %d j %d", i, j)
k = 0
kk = 1
max_stepsize = 32
stepsize = max_stepsize
while (True):
for jj in xrange(j - kk + 1, j + 1):
for ii in xrange(i - kk + 1, i + 1):
# XXX Not clear this just in time thresholding is very
# efficient, since it duplicates work already done in the
# previous iteration, maybe it should cache some of the
# thresholding? (just in time thresholding is known to be
# very beneficial for big maps)
b = np_graythreshold(a[jj:jj+kk, ii:ii+kk], threshold)
if (b.all()):
k = kk
break
else:
# Filter didn't fit for any ii, try next jj
continue
# Filter did fit, try next size
break
else:
# Filter didn't fit, divide step and try a smaller size
if ((stepsize == 0) or (kk == 1)):
# kk will be 1 if even the first iteration fails, abort in that
# case too
break
kk -= stepsize
stepsize = stepsize / 2
continue
# Filter did fit, divide step and try a larger size
if (stepsize == 0):
break
kk += stepsize
# Can't bisect until the filter fails to fit, otherwise it would only
# test as far as max_stepsize*2 - 1 (eg for 16, it would test upto
# 16+8+4+2+1=32-1)
if (stepsize != max_stepsize):
stepsize = stepsize / 2
logger.info("found max %d", k)
return k
def np_findmaxfiltersize(a, i, j, threshold):
"""
Find the largest nxn erode filter size that fits and contains the provided
array coordinate
@param a boolean array
@param x,y coordinates to start probing the filter size
@return int with max filter size
"""
logger.info("i %d j %d", i, j)
# XXX Missing padding the original if i, j is too close to the edge or tune
# parameters so that part is not probed?
# Find the largest nxn erode filter size that contains the provided array
# coordinate (so the provided coordinate can be as early as the top left or
# as late as the bottom right of the nxn erode filter)
k = 0
kk = 1
while (True):
for jj in xrange(j- kk + 1, j + 1):
# Test column by column to be able to restart the search skipping
# columns.
# XXX This is a dubious optimization, only a perf win vs. the naive
# triple loop in very large k sizes like 64, for sizes around 16
# the naive and non-naive function time is negligible (less
# than the log's default time precision).
ii = iii = i - kk + 1
while (ii < (i + 1)):
# Probing the filter with size kk with top left corner in ii,jj
b = np_graythreshold(a[jj:jj+kk,iii], threshold)
# XXX Make the bounds test better, it's redundant to check for
# jj here and bounds could be clamped elsewhere
if (
(jj >= 0) and (jj + kk <= a.shape[0]) and
(ii >= 0) and (ii + kk <= a.shape[1]) and
b.all()
):
# This column of the filter fits
if (iii == (ii + kk - 1)):
# This is the last column of the filter, record the new
# max filter size and early exit
k = kk
break
# Continue until the last column of the filter size being
# tested is hit
iii += 1
else:
# This column doesn't fit at this jj, ii, try the next ii at
# this filter size
ii += 1
iii = ii
else:
# No early exit, so filter wasn't found at this jj, try next jj
continue
# Early exit, so this filter size was found to fit, done testing
# this j,i at this filter size
break
else:
# The loop didn't early exit, this means a kk x kk containing i,j
# coudln't fit, no larger filter sizes containing i,j will fit
# either, done
break
# Try next filter size
kk += 1
logger.info("found max k %d", k)
return k
def np_floodfillerode(a, x, y, erosion_diameter):
"""
@param a Boolean ndarray
@param x,y position inside the ndarray to start flooding
@param erosion_diameter, flood only if all the pixels in the
erosion_diameter / 2, erosion_diameter/2 + 1 are true
@return Python set of j, i tuples
"""
logger.info("x %d y %d", x, y)
# XXX This needs to add padding
stack = []
if (a[y, x]):
stack.append((y, x))