Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion imagepy/app/imagepy.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import time, threading
sys.path.append('../../../')
import wx.lib.agw.aui as aui
from sciwx.widgets import MenuBar, ToolBar, ChoiceBook, ParaDialog, WorkFlowPanel, ProgressBar
from sciwx.widgets import MenuBar, RibbonBar, ToolBar, ChoiceBook, ParaDialog, WorkFlowPanel, ProgressBar
from sciwx.canvas import CanvasNoteBook
from sciwx.grid import GridNoteBook
from sciwx.mesh import Canvas3DNoteBook
Expand Down Expand Up @@ -147,6 +147,8 @@ def load_widget(self, data):

def init_menu(self):
self.menubar = MenuBar(self)
# self.menubar = RibbonBar(self)
# self.auimgr.AddPane( self.menubar, aui.AuiPaneInfo() .CaptionVisible(False) .Top() .PinButton( True ).Dock().Resizable().MinSize(wx.Size(1000, 130)).FloatingSize( wx.DefaultSize ).Layer(5) )

def init_tool(self):
sizer = wx.BoxSizer(wx.VERTICAL)
Expand Down
8 changes: 4 additions & 4 deletions imagepy/app/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"""
import os, sys, os.path as osp
from glob import glob
from sciapp.action import Macros, Widget#, Report
from sciapp.action import Macros, Widget, Report
from .. import root_dir
from .manager import DocumentManager, DictManager
from codecs import open
Expand All @@ -23,9 +23,9 @@ def extend_plugins(path, lst, err):
rst = []
for i in lst:
if isinstance(i, tuple) or i=='-': rst.append(i)
elif i[-3:] == 'rpt': pass
#pt = os.path.join(root_dir,path)
#rst.append(Report(i[:-4], pt+'/'+i))
elif i[-3:] == 'rpt':
pt = os.path.join(root_dir,path)
rst.append(Report(i[:-4], pt+'/'+i))
elif i[-3:] in {'.md', '.mc', '.wf'}:
p = os.path.join(os.path.join(root_dir, path), i).replace('\\','/')
rst.append(Macros(i[:-3], ['Open>{"path":"%s"}'%p]))
Expand Down
2 changes: 1 addition & 1 deletion imagepy/data/config.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[["uistyle", "imagepy", null], ["mea_style", {"color": [0, 0, 255], "fcolor": [255, 255, 255], "fill": false, "lw": 2, "tcolor": [0, 255, 0], "size": 12}, null], ["mark_style", {"color": [0, 255, 0], "fcolor": [255, 255, 255], "fill": false, "lw": 1, "tcolor": [255, 0, 0], "size": 8}, null], ["recent", ["C:/Users/54631/Desktop/\u6d77\u51b0\u62a5\u4ef7/testmacros.mc", "C:\\Users\\Administrator\\Downloads\\\u7d20\u6750\u2014\u8f66\u5934\\\u6d4b\u8bd5-JK1-\u52ff\u5220\\20170201\\In-20170201151126911-\u6842J73220-\u9ec4-qj-1.jpg", "C:/Users/Administrator/Desktop/imagepy/imagepy/plugins/demoplugin/menus/Demos/Macros Demo/Macros Gaussian Invert.mc", "DEM.mc"], null], ["roi_style", {"color": [255, 255, 0], "fcolor": [255, 255, 255], "fill": false, "lw": 1, "tcolor": [255, 255, 0], "size": 8}, null], ["language", "English", null]]
[["language", "English", null], ["roi_style", {"color": [255, 255, 0], "fcolor": [255, 255, 255], "fill": false, "lw": 1, "tcolor": [255, 255, 0], "size": 8}, null], ["recent", ["C:/Users/54631/Desktop/\u6d77\u51b0\u62a5\u4ef7/testmacros.mc", "C:\\Users\\Administrator\\Downloads\\\u7d20\u6750\u2014\u8f66\u5934\\\u6d4b\u8bd5-JK1-\u52ff\u5220\\20170201\\In-20170201151126911-\u6842J73220-\u9ec4-qj-1.jpg", "C:/Users/Administrator/Desktop/imagepy/imagepy/plugins/demoplugin/menus/Demos/Macros Demo/Macros Gaussian Invert.mc", "DEM.mc"], null], ["mark_style", {"color": [0, 255, 0], "fcolor": [255, 255, 255], "fill": false, "lw": 1, "tcolor": [255, 0, 0], "size": 8}, null], ["mea_style", {"color": [0, 0, 255], "fcolor": [255, 255, 255], "fill": false, "lw": 2, "tcolor": [0, 255, 0], "size": 12}, null], ["uistyle", "imagepy", null]]
2 changes: 1 addition & 1 deletion imagepy/menus/Analysis/statistic_plg.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def run(self, ips, imgs, para = None):
img = imgs[i] if msk is None else imgs[i][msk]
maxv = img.max()
if maxv==0:continue
ct = np.histogram(img, maxv, [1,maxv+1])[0]
ct = np.histogram(img, maxv+1, [0,maxv])[0]
titles = ['slice','value','count']
dt = [[i]*len(ct), list(range(maxv+1)), ct]
if not para['slice']:
Expand Down
2 changes: 1 addition & 1 deletion imagepy/menus/File/new_plg.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import numpy as np

class Plugin(Free):
title = 'New Image'
title = 'New'
para = {'name':'Undefined','width':300, 'height':300, 'type':'8-bit','slice':1}
view = [(str, 'name', 'name', ''),
(int, 'width', (1,10240), 0, 'width', 'pix'),
Expand Down
Binary file added imagepy/menus/Plugins/Coins Report.rpt
Binary file not shown.
4 changes: 2 additions & 2 deletions imagepy/menus/Process/Threshold/threshold_plgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class Niblack(Filter):
(float, 'k', (0, 1), 2, 'offset', '')]

def run(self, ips, snap, img, para = None):
if para['size']%2==0: return IPy.alert('size must be Odd')
if para['size']%2==0: return self.app.alert('size must be Odd')
img[:] = (snap>threshold_niblack(snap, para['size'], para['k']))*ips.range[1]

class Sauvola(Filter):
Expand All @@ -92,7 +92,7 @@ class Sauvola(Filter):
(float, 'k', (0, 1), 2, 'offset', '')]

def run(self, ips, snap, img, para = None):
if para['size']%2==0: return IPy.alert('size must be Odd')
if para['size']%2==0: return self.app.alert('size must be Odd')
img[:] = (snap>threshold_sauvola(snap, para['size'], para['k']))*ips.range[1]

plgs = [SimpleThreshold, Auto, '-', Local, Niblack, Sauvola, '-', Hysteresis]
2 changes: 1 addition & 1 deletion sciapp/action/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
from .plugin.mea_tools import *
from .plugin.shp_tools import *
from .plugin.roi_tools import *
from .advanced import Filter, Free, Simple, Table, Macros, Widget, dataio
from .advanced import Filter, Free, Simple, Table, Macros, Widget, dataio, Report
3 changes: 2 additions & 1 deletion sciapp/action/advanced/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
from .table import Table
from .free import Free
from .macros import Macros
from .widget import Widget
from .widget import Widget
from .report import Report
66 changes: 66 additions & 0 deletions sciapp/action/advanced/report.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 29 01:48:23 2016
@author: yxl
"""
import wx
from sciapp import app
from sciapp.action.advanced.dataio import ReaderManager
# from imagepy.core.manager import ReaderManager, ViewerManager
from sciwx.widgets.propertygrid import GridDialog
from sciapp.util import xlreport
from time import time
import openpyxl as pyxl

class Report:
def __init__(self, title, cont):
self.title = title
self.cont = cont

def __call__(self): return self

def runasyn(self, wb, info, key, para = None, callback = None):
self.app.add_task(self)
for i in para:
if i in key and key[i][0] == 'img':
ips = self.app.get_img(para[i])
para[i] = ips if ips is None else ips.img

if i in key and key[i][0] == 'tab':
tps = self.app.get_table(para[i])
para[i] = tps if tps is None else tps.data

start = time()
xlreport.fill_value(wb, info, para)
wb.save(para['path'])
self.app.info('%s: cost %.3fs'%(self.title, time()-start))
self.app.remove_task(self)
if callback!=None:callback()

def start(self, app, para=None, callafter=None):
self.app = app
wb = pyxl.load_workbook(self.cont)
xlreport.repair(wb)
info, key = xlreport.parse(wb)

if para is not None:
return self.runasyn(wb, info, para, callafter)
dialog = GridDialog(self.app, self.title, info, key)
rst = dialog.ShowModal()
para = dialog.GetValue()

dialog.Destroy()
if rst != 5100: return
filt = ['XLSX', 'xlsx', 'xlsx']
path = self.app.get_path('Save..', filt, 'save')
if not path: return
para['path'] = path
self.app.record_macros('{}>{}'.format(self.title, para))
self.runasyn(wb, info, key, para, callafter)

def show_rpt(data, title):
wx.CallAfter(Report(title, data).start)

# ViewerManager.add('rpt', show_rpt)
def read_rpt(path): return path
ReaderManager.add('rpt', read_rpt, tag='rpt')
5 changes: 4 additions & 1 deletion sciapp/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def __init__(self, asyn=True):
self.asyn = asyn
self.managers = {}
self.img_manager = self.manager('img')
#self.wimg_manager = self.manager('wimg')
self.wimg_manager = self.manager('wimg')
self.tab_manager = self.manager('tab')
#self.wtab_manager = self.manager('wtab')
self.mesh_manager = self.manager('mesh')
Expand Down Expand Up @@ -40,6 +40,9 @@ def show_img(self, img, name):
self.img_manager.add(img.name, img)
print(img.info)

def add_img_win(self, win, name):
self.wimg_manager.add(name, win)

def close_img(self, name):
self.img_manager.remove(name)
print('close image:', name)
Expand Down
116 changes: 116 additions & 0 deletions sciapp/util/xlreport.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import openpyxl as pyxl
from openpyxl.utils.units import cm_to_EMU, EMU_to_pixels
from io import BytesIO
from openpyxl.drawing.image import Image
from PIL import Image as PImage
import numpy as np
import pandas as pd
from copy import copy

if not '.rpt' in pyxl.reader.excel.SUPPORTED_FORMATS:
pyxl.reader.excel.SUPPORTED_FORMATS += ('.rpt',)

def parse(wb):
rst, key = [], {}
for ws in wb.worksheets:
rst.append((ws.title, []))
for row in ws.rows:
for cell in row:
if not isinstance(cell.value, str):continue
if cell.value[0]+cell.value[-1] != '{}': continue
cont = cell.value[1:-1].strip()
tp = cont.split(' ')[0]
cont = cont[len(tp):].strip()
note, value = 'no description', None
if '#' in cont:
note = cont.split('#')[-1].strip()
cont = cont[:cont.index('#')].strip()
if '=' in cont:
value = cont.split('=')[1].strip()
name = cont[:cont.index('=')].strip()
else: name = cont

rst[-1][-1].append(((cell.row, cell.col_idx),
[tp, name, value, note]))
key[name] = [tp, name, value, note]
return rst, key

def trans(img, W, H, margin, scale):
h, w = img.shape[:2]
h2, w2 = int(h/margin), int(w/margin)
if scale:
if W/H > w/h: w2 = int(W/H*h2)
if H/W > h/w: h2 = int(H/W*w2)
newshp = (h2, w2) if img.ndim==2 else (h2, w2, 3)
blank = np.ones(newshp, dtype=np.uint8) * 255
blank[(h2-h)//2:(h2-h)//2+h, (w2-w)//2:(w2-w)//2+w] = img
return blank

def add_image(wb, ws, pos, key, img):
if img is None: return
w, h, margin, scale = eval(key[2])
img = trans(img, w, h, margin, scale==0)
img = PImage.fromarray(img)
image_file = BytesIO()
img.save(image_file, 'png')
ref = BytesIO(image_file.getvalue())
image = Image(img)
image.ref = ref
image.height = EMU_to_pixels(cm_to_EMU(h))
image.width = EMU_to_pixels(cm_to_EMU(w))
wb[ws].add_image(image, wb[ws].cell(*pos).coordinate)

def add_table(wb, ws, pos, key, data):
if data is None: return
vs = data.values
idx, cols = data.index, data.columns
dr, dc, ir, ic = 1, 1, 0, 0
if key[2] != None: dr, dc, ir, ic = eval(key[2])
for r in range(vs.shape[0]):
if ir!=0: wb[ws].cell(pos[0]+r*dr, pos[1]+ir, idx[r])
for c in range(vs.shape[1]):
if ic!=0: wb[ws].cell(pos[0]+ic, pos[1]+c*dc, cols[c])
for r in range(vs.shape[0]):
for c in range(vs.shape[1]):
wb[ws].cell(pos[0]+r*dr, pos[1]+c*dc, vs[r,c])

def fill_value(wb, infos, para):
for worksheet in infos:
ws, info = worksheet
for pos, key in info:
if not key[1] in para: continue
if key[0] in ('str', 'int', 'float', 'bool', 'txt', 'list', 'date'):
wb[ws].cell(pos[0], pos[1], para[key[1]])
if key[0] == 'img':
add_image(wb, ws, pos, key, para[key[1]])
if key[0] == 'tab':
add_table(wb, ws, pos, key, para[key[1]])

def repair(wb):
for ws in wb.worksheets:
for cr in ws.merged_cells:
ltc = ws.cell(cr.min_row, cr.min_col)
vb, hb = ltc.border.left, ltc.border.top
for r in range(cr.min_row, cr.max_row+1):
for c in range(cr.min_col, cr.max_col+1):
cur = copy(ws.cell(r, c).border)
cur.left, cur.right = copy(vb), copy(vb)
cur.top, cur.bottom = copy(hb), copy(hb)
ws.cell(r, c).border = cur

if __name__ == '__main__':
rst = pd.read_csv('rst.csv')
img = np.arange(10000, dtype=np.uint8).reshape((100,100))
data = {'Sample_ID':'Coins-0001', 'Operator_Name':'YX Dragon', 'Date':'2019-02-05',
'Record':rst, 'Original_Image':img, 'Mask_Image':img}

wb = pyxl.load_workbook('Coins Report.xlsx',)
repair(wb)
ws = wb.active


infos = parse(wb)
print(infos)
fill_value(wb, infos, data)
wb.save('new.xlsx')

2 changes: 1 addition & 1 deletion sciwx/canvas/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def move(self, dx, dy, coord='win'):
self.update()

def on_size(self, event):
if max(self.GetClientSize())>20:
if max(self.GetClientSize())>20 and self.images[0].img is not None:
self.initBuffer()
if len(self.images)+len(self.marks)==0: return
if self.conbox[2] - self.conbox[0] > 1: self.update()
Expand Down
2 changes: 2 additions & 0 deletions sciwx/canvas/mcanvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ def on_scroll(self, event):
self.canvas.on_idle(event)

def on_idle(self, event):
if self.image.img is None:
return
image, info = self.image, self.lab_info.GetLabel()
imgs = image.slices, image.channels, image.cn, image.cur
selfs = self.pages ,self.chans, self.cn, self.cur
Expand Down
Loading