def find(self, img): self.img = img coreimg, cladimg = self._difcore(img) # cv2.imshow("clad edge", cladimg[::4,::4]) # cv2.waitKey() sets = SETTING() if 'thresholdSize' in sets.keys(): hight = sets['thresholdSize'].get("core") coreimg = ExtractEdge().directThr(coreimg, hight) else: coreimg = ExtractEdge().directThr(coreimg) # coreimg = ExtractEdge().run(coreimg) # cladimg = ExtractEdge().run(cladimg) if 'thresholdSize' in sets.keys(): hight = sets['thresholdSize'].get("clad", 40) cladimg = ExtractEdge().directThr(cladimg, hight) else: cladimg = ExtractEdge().directThr(cladimg) # cladimg = cv2.bilateralFilter(cladimg, 20, 80, 75) # cv2.imshow("cladimg edge", cladimg[::4,::4]) # cv2.waitKey() coreResult = PickHullCircle().run(coreimg) cladResult = PickHullCircle().run(cladimg) print 'amp', self.SET['ampPixSize'], self.SET['fiberType'] self.result['core'] = coreResult['ellipese'] self.result['coreResult'] = coreResult self.result['clad'] = cladResult['ellipese'] self.result['cladResult'] = cladResult self.result['showResult'] = self.getResult() return self.result
def __init__(self, ): Thread.__init__(self) QObject.__init__(self) super(ModelCV, self).__init__() self.setDaemon(True) self.IS_RUN = True self.isSharp = IsSharp() self.show = Cv2ImShow() self.save = Cv2ImSave() self.eresults = False self.result2Show = {} self.decorateMethod = decorateMethod("G652") self.getRawImg = GetRawImg() self.imgmaxlen = 5 self.imgQueue = collections.deque(maxlen=self.imgmaxlen) self.fiberResult = {} self.Oceanoptics = OceanOpticsTest() self.classify = classifyObject('G652') self.pdfparameter = SETTING()['pdfpara'] self.dbparameter = SETTING()['dbpara'] # self.sharps = collections.deque(maxlen=15) try: # self.focuser = LiveFocuser() self.focuser = AbsFocuser() # self.focuser.start() except serial.serialutil.SerialException as e: print e
def find(self, img): self.img = img coreimg, cladimg = self._difcore(img) sets = SETTING() if 'thresholdSize' in sets.keys(): hight = sets['thresholdSize'].get("core") coreimg = ExtractEdge().directThr(coreimg, hight) else: coreimg = ExtractEdge().directThr(coreimg) # coreimg = ExtractEdge().run(coreimg) cladimg = ExtractEdge().run(cladimg) # cv2.imshow('core', coreimg[::4, ::4]) # cv2.waitKey() # cv2.imshow('clad', cladimg[::4, ::4]) # cv2.waitKey() coreResult = PickCircle().run(coreimg) cladResult = PickOctagon().run(cladimg) print 'start octagon test', cladResult.keys(), cladResult['ellipese'] self.result['core'] = coreResult['ellipese'] self.result['coreResult'] = coreResult self.result['clad'] = cladResult['ellipese'] self.result['cladResult'] = cladResult self.result['showResult'] = self.getResult() return self.result
def test_updateSets_args(): s = SETTING("Default") s.updates() assert "set" not in s.keys() assert "testsetdict" not in s.keys() s.updates("set", {"testsetdict": "dict"}) assert s.get("testset") == ".json" assert s.get("testsetdict") == "dict"
def __init__(self, ): super(MetaClassify, self).__init__() # self.arg = arg self.result = {} self.SET = SETTING() self.ampRatio = self.SET.get("ampPixSize", 1) self.medianlimitFilterCore = MedianFilter() self.medianlimitFilterClad = MedianFilter()
def differCore(): img = getImage("IMG\\midoc.BMP") print 'get shape', img.shape # cv2.imshow('mid', img[::4,::4]) # cv2.waitKey() corecore = SETTING()["corepoint"] print getCircleMeans((corecore, 10), img) minRange, maxRange = SETTING()["coreRange"] img = getFilterImg(corecore, img, minRange, maxRange) # cv2.imshow('dif', img[::4, ::4]) # cv2.waitKey() # circle = print getCircleMeans((corecore, 100), img)
def _greenLight(self, img): if isinstance(img, np.ndarray): corey, corex = SETTING()["corepoint"] minRange, maxRange = SETTING()["coreRange"] green = sliceImg(img[::, ::, 1], (corex, corey), maxRange) blue = sliceImg(img[::, ::, 2], (corex, corey), maxRange) self.allblue = img[::, ::, 2].sum() / 255 self.green = green.sum() / 255 self.blue = blue.sum() / 255 self.allgreen = img[::, ::, 1].sum() / 255 - self.green self.pdfparameter['corelight'] = "%0.2f" % self.blue self.pdfparameter['cladlight'] = "%0.2f" % self.allgreen self.returnCoreLight.emit("%0.2f" % (self.blue), "%0.2f" % (self.allgreen))
def outer_fill(img, core=SETTING()['corepoint'], radius=0, value=0): if not radius: return img sharp = img.shape print sharp, core ymax = sharp[0] xmax = sharp[1] y0, x0 = core yranges = xrange(y0 - radius, y0 + radius) for y in yranges: x00, x01 = -(radius**2 - (y - y0)**2)**0.5 + x0, (radius**2 - (y - y0)**2)**0.5 + x0 x00, x01 = int(x00), int(x01) if x00 < x01: img[0:x00, y].fill(value) img[x01:xmax, y].fill(value) else: img[:, y].fill(value) pass if ymax == radius * 2: return img img[:, :(y0 - radius)].fill(value) img[:, (y0 + radius):].fill(value) # (x-x0)^2 +(y-y0)^2 = R^2 # ±(R - (y-y0)^2)**0.5 +x0 return img
def DecorateImg(origin, ellipses, result=False): if SETTING().get("fiberType") in ("20400", "G652"): return decorateDoubleCircle(origin, ellipses, result) if isinstance(ellipses, dict): return decorateOctagon(origin, ellipses, result) else: return oldDecorateImg(origin, ellipses, result)
def __init__(self, ): """ init """ super(CV2MethodSet, self).__init__() self.Show = Cv2ImShow() self.Save = Cv2ImSave() self.DPick = DynamicPick() self.CircleIndex = cv2CircleIndex() self.SET = SETTING()
def test_fill_mid(): SETTING().keyUpdates("capillary", "test") img = randomImg("IMG\\emptytuple\\eptlight0\\") coreimg = img[::, ::, 0].copy() coreimg = inner_fill(coreimg, radius=100) cladimg = img[::, ::, 1].copy() cladimg = outer_fill(cladimg, radius=100)
def __init__(self, ): super(GetRawImg, self).__init__() self.SET = SETTING() self.limit = 2592 * 1944 # if self.SET.get("ifcamera", False): try: self.hand = mdp.initCamera() except Exception as e: raise e
def test_repeat_G652(): sets = SETTING() sets.updates('G652', 'test') print 'sets', sets resultgetcore = [] resultgetclad = [] for img in yieldImg("IMG\\G652\\mid\\"): result = G652Classify().find(img) core, clad = result['coreResult'], result['cladResult'] print core['ellipese'], clad['ellipese'] assert core['longAxisLen'] > 0.5 assert core['shortAxisLen'] > 0.5 assert core['longAxisLen'] > core['shortAxisLen'] ratio = core['shortAxisLen'] / core['longAxisLen'] assert ratio > 0.9 _1, _2 = core['corePoint'][0].tolist() radius = core['longAxisLen'] + core['shortAxisLen'] / 2 print _1, _2, radius resultgetcore.append([_1, _2, radius]) print clad['ellipese'], clad['ellipese'] assert clad['longAxisLen'] > 0.5 assert clad['shortAxisLen'] > 0.5 assert clad['longAxisLen'] > clad['shortAxisLen'] ratio = clad['shortAxisLen'] / clad['longAxisLen'] assert ratio > 0.9 _1, _2 = clad['corePoint'][0].tolist() radius = clad['longAxisLen'] + clad['shortAxisLen'] / 2 print _1, _2, radius resultgetclad.append([_1, _2, radius]) resultarray = np.array(resultgetcore) # print resultarray std = np.std(resultarray, axis=0) x, y, z = std print 'std', x, y, z assert z < 0.5 resultarray = np.array(resultgetclad) # print resultarray std = np.std(resultarray, axis=0) x, y, z = std print 'std', x, y, z assert z < 1.5
def test_sliceImg(): SETTING().keyUpdates("Default") img = GetImage().get("IMG\\midoctagon\\mid1.BMP", "gray") if img.shape == (1944, 2592): print 'slice shape', img.shape corey, corex = SETTING()["corepoint"] minRange, maxRange = SETTING()["coreRange"] img = sliceImg(img, (corex, corey), maxRange) print 'slice shape', img.shape assert img.shape == (160, 160) img = GetImage().get("IMG\\midoctagon\\mid1.BMP", "color") if img.shape == (1944, 2592, 3): print 'slice shape', img.shape corey, corex = SETTING()["corepoint"] minRange, maxRange = SETTING()["coreRange"] img = sliceImg(img, (corex, corey), maxRange) print 'slice shape', img.shape assert img.shape == (160, 160, 3)
def drawCoreCircle(img): SET = SETTING() corecore = SET.get("corepoint", (1296, 972)) core = [corecore, 1] # print "corecorex, corecorey", corecorex, corecorey minRange, maxRange = SET.get("coreRange") # cv2.circle(img, (int(core[0][0]), int(core[0][1])), int(maxRange), (255, 255, 255), 4) cv2.circle(img, (int(core[0][0]), int(core[0][1])), int(minRange), (0, 0, 0), 4) x0, y0 = corecore x1, y1 = x0 + minRange, y0 x2, y2 = x0 + maxRange, y0 cv2.line(img, (x1, y1), (x2, y2), (255, 0, 0), 4) x1, y1 = x0, y0 + minRange x2, y2 = x0, y0 + maxRange cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255), 4) x1, y1 = x0 - minRange, y0 x2, y2 = x0 - maxRange, y0 cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255), 4) x1, y1 = x0, y0 - minRange x2, y2 = x0, y0 - maxRange cv2.line(img, (x1, y1), (x2, y2), (255, 255, 255), 4) if SET.get("draw_clad", False): minRange, maxRange = SET.get("cladRange") cv2.circle(img, (int(core[0][0]), int(core[0][1])), int(maxRange), (0, 0, 0), 4) cv2.circle(img, (int(core[0][0]), int(core[0][1])), int(minRange), (255, 255, 255), 4) return img
def test_other_set(): s = SETTING('G652') print s.store assert 'G652' == s.get('fiberType') s = SETTING('octagon') print s.store print 'singleton2', id(s) assert 'octagon' != s.get('fiberType')
class MetaClassify(CV2MethodSet): """docstring for MetaClassify""" def __init__(self, ): super(MetaClassify, self).__init__() # self.arg = arg self.result = {} self.SET = SETTING() self.ampRatio = self.SET.get("ampPixSize", 1) self.medianlimitFilterCore = MedianFilter() self.medianlimitFilterClad = MedianFilter() # @timing def find(self, img): contours, hierarchys = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) self._filter(contours, hierarchys) return self.result def _filter(self, contours, hierarchys): pass def getResult(self): coreResult = self.result.get('coreResult', False) cladResult = self.result.get('cladResult', False) if coreResult and cladResult: coreCore = coreResult["corePoint"].tolist()[0] cladCore = cladResult["corePoint"].tolist()[0] coreRadius = (coreResult["longAxisLen"] + coreResult["shortAxisLen"]) / 2 cladRadius = (cladResult["longAxisLen"] + cladResult["shortAxisLen"]) / 2 concentricity = ((coreCore[0] - cladCore[0])**2 + (coreCore[1] - cladCore[1])**2)**0.5 concentricity = concentricity * self.ampRatio coreMidRadius = self.ampRatio * coreRadius # self.medianlimitFilterCore.append(coreMidRadius) # coreMidRadius = self.medianlimitFilterCore.get() cladMidRadius = self.ampRatio * cladRadius # cladMidRadius = self.medianlimitFilterClad.append(cladMidRadius) # cladMidRadius = self.medianlimitFilterClad.get() # cladMidRadius = (cladRadius[0] + cladRadius[1]) coreRness = self.ampRatio * abs(coreResult["longAxisLen"] - coreResult["shortAxisLen"]) cladRness = self.ampRatio * abs(cladResult["longAxisLen"] - cladResult["shortAxisLen"]) return (concentricity, coreMidRadius, cladMidRadius, coreRness, cladRness) else: print 'error find core or clad' return ()
def writePdfabs(dir_): updates = SETTING().get('pdfpara') htmlpara.update(updates) newbody = originHTML.format(**htmlpara) # with open('t.html', 'wb') as f: # f.write(newbody) # f.close() printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_) printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def test_class_G652(): SETTING().keyUpdates('G652', 'test') print 'set', SETTING() big = G652Classify() img = GetImage().get("IMG\\G652\\mid\\g652mid.BMP", colour='colour') # img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR) print img.shape result = big.find(img) core, clad = result['coreResult'], result['cladResult'] print core['ellipese'], clad['ellipese'], result['cladResult'].keys() assert core['longAxisLen'] > 0.5 assert core['shortAxisLen'] > 0.5 assert core['longAxisLen'] > core['shortAxisLen'] ratio = core['shortAxisLen'] / core['longAxisLen'] assert ratio > 0.9 # cv2.imshow("clad", clad['plot'][::4,::4]) # cv2.waitKey() assert clad['longAxisLen'] > 0.5 assert clad['shortAxisLen'] > 0.5 assert clad['longAxisLen'] > clad['shortAxisLen'] ratio = clad['shortAxisLen'] / clad['longAxisLen'] assert ratio > 0.9
def test_class_rough(): SETTING("test").keyUpdates('20400') big = Big20400Classify() # for img in yieldImg("IMG\\20400\\"): # img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR) img = GetImage().get("IMG\\20400\\size1.bmp") print img.shape result = big.find(img) core, clad = result['coreResult'], result['cladResult'] print core['ellipese'], clad['ellipese'], result['cladResult'].keys() assert core['longAxisLen'] > 0.5 assert core['shortAxisLen'] > 0.5 assert core['longAxisLen'] > core['shortAxisLen'] ratio = core['shortAxisLen'] / core['longAxisLen'] assert ratio > 0.9
def test_octagon_class_find_result(): SETTING().keyUpdates('octagon', 'centerImg') img = getImage("IMG\\midoctagon\\mid1.BMP") result = OctagonClassify().find(img) keys = ['core', 'clad', 'coreResult', 'cladResult'] for k in keys: assert k in result.keys() keys = ['corePoint', 'longAxisLen', 'shortAxisLen'] for k in keys: assert k in result.get('coreResult', {}).keys() assert k in result.get('cladResult', {}).keys() assert isinstance(result['core'], tuple) assert isinstance(result['clad'], tuple) assert isinstance(result['cladResult']['shortPlot'], tuple) assert len(result['cladResult']['shortPlot']) == 2 assert isinstance(result['cladResult']['longPlot'], tuple) assert len(result['cladResult']['longPlot']) == 2
def test_repeat_octagon(): sets = SETTING() resultget = [] for img in yieldImg("IMG\\repeat\\octagon\\"): img = ExtractEdge().run(img) img = cv2.medianBlur(img, 11) result = PickOctagon().run(img) _1, _2 = result['corePoint'][0].tolist() radius = result['longAxisLen'] + result['shortAxisLen'] / 2 print _1, _2, radius resultget.append([_1, _2, radius]) resultarray = np.array(resultget) # print resultarray std = np.std(resultarray, axis=0) x, y, z = std * 0.088 print 'std', x, y, z assert z < 0.5
def test_classify_tuple(): SETTING().keyUpdates("capillary", "test") img = randomImg("IMG\\emptytuple\\eptlight0\\") # cv2.imshow("filled",img[::4,::4]) # cv2.waitKey() classify = Capillary() result = classify.find(img) core, clad = result['coreResult'], result['cladResult'] print core['ellipese'], clad['ellipese'], result['cladResult'].keys() assert core['longAxisLen'] > 0.5 assert core['shortAxisLen'] > 0.5 assert core['longAxisLen'] > core['shortAxisLen'] ratio = core['shortAxisLen'] / core['longAxisLen'] assert ratio > 0.8 assert clad['longAxisLen'] > 0.5 assert clad['shortAxisLen'] > 0.5 assert clad['longAxisLen'] > clad['shortAxisLen'] ratio = clad['shortAxisLen'] / clad['longAxisLen'] assert ratio > 0.8
def inner_fill(img, core=SETTING()['corepoint'], radius=0, value=0): if not radius: return img sharp = img.shape print sharp, core ymax = sharp[0] xmax = sharp[1] y0, x0 = core yranges = xrange(y0 - radius, y0 + radius) # xranges = [] for y in yranges: x00, x01 = -(radius**2 - (y - y0)**2)**0.5 + x0, (radius**2 - (y - y0)**2)**0.5 + x0 x00, x01 = int(x00), int(x01) # xranges.append((x00, x01)) # print 'fill',y , x00, x01 if x00 < x01: img[x00:x01, y].fill(value) # (x-x0)^2 +(y-y0)^2 = R^2 # ±(R - (y-y0)^2)**0.5 +x0 return img
def run(self, img): blurindex = SETTING()["medianBlur"].get("corefilter", 3) img = cv2.medianBlur(img, blurindex) # cv2.imshow("img", img[::4, ::4]) # cv2.waitKey() contours, hierarchys = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) tempPlots = np.ones(img.shape) * 255 print 'get contours len', len(contours) if len(contours) == 0: raise ClassCoreError elif len(contours) == 1: mergedpoints = contours[0] else: mergedpoints = np.concatenate(contours[1:]) ellipse = cv2.fitEllipse(mergedpoints) result = self._getResult(ellipse) result['ellipese'] = ellipse cv2.ellipse(tempPlots, ellipse, (0, 255, 255)) result['plot'] = tempPlots result['contour'] = mergedpoints return result
def run(self, img): """ :findContours->convexHull->sortMaxPointsDistance ->calculateVerticalPoint->result: Long & short axis :param img: :return: """ blurindex = SETTING()["medianBlur"].get("cladfilter", 3) img = cv2.medianBlur(img, blurindex) # img = cv2.adaptiveBilateralFilter # img = cv2.bilateralFilter(img, 5, 80, 75) # img = EdgeFuncs().close(img,kernelLen=3) # print 'get blur index ', blurindex contours, hierarchys = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) tempPlots = np.ones(img.shape) * 255 print 'get contours len', len(contours) for contour in contours: cv2.drawContours(tempPlots, contour, -1, (0, 0, 255)) # for contour in contours: # cv2.drawContours(tempPlots, contour, -1, (0, 0, 255)) if len(contours) == 0: raise ClassCoreError elif len(contours) == 1: mergedpoints = contours[0] else: mergedpoints = np.concatenate(contours[1:]) points = cv2.convexHull(points=mergedpoints) longAxis = self._getLongAxit(points) result = {} result['angle'] = longAxis[3] x, y = tuple(longAxis[1][0].tolist()), tuple(longAxis[2][0].tolist()) result['longPlot'] = (x, y) cv2.line(tempPlots, x, y, (0, 255, 0), 8) midPoint = longAxis[1][0] + longAxis[2][0] midPointf = midPoint / 2 midPoint = midPoint // 2 getVerticalPoint = mergedpoints.tolist() getVerticalPoint.sort(key=lambda x: np.linalg.norm(x - midPoint)) # getVerticalPoint = getVerticalPoint[:-2] tempCounters = (getVerticalPoint[0], getVerticalPoint[-1]) getVerticalPoint = self._getHalfList(getVerticalPoint) getVerticalPoint.sort( key=lambda x: abs(self.angleRatio([midPoint], longAxis[1], x))) # getVerticalPoint.sort(key=lambda x: abs(self.horizonalRatio45([midPoint], longAxis[1], x))) result['angle'] = self.angleRatio([midPoint], longAxis[1], getVerticalPoint[-1]) # print 'get x y ', x, y, midPoint, longAxis # pdb.set_trace() x, y = tuple(midPoint.tolist()), tuple(getVerticalPoint[0][0]) cv2.line(tempPlots, x, y, (0, 255, 0), 8) result['shortPlot'] = (x, y) result.update( self._getResult(longAxis, midPoint, getVerticalPoint, tempCounters)) # print 'result[\'contour\']', result['contour'] ellipse = cv2.fitEllipse(result['contour']) # cv2.ellipse(tempPlots, ellipse, (0, 25, 25), 4) result['plot'] = tempPlots result['ellipese'] = ellipse for circleCore in result['contour']: circleCore = tuple(circleCore[0].tolist()) cv2.circle(tempPlots, circleCore, 40, (0, 255, 0), lineType=4) return result
from setting.orderset import SETTING SETTING().keyUpdates('octagon', 'centerImg') import cv2 import numpy as np import pdb from pattern.getimg import getImage from pattern.classify import OctagonClassify def test_octagon_class_find_result(): SETTING().keyUpdates('octagon', 'centerImg') img = getImage("IMG\\midoctagon\\mid1.BMP") result = OctagonClassify().find(img) keys = ['core', 'clad', 'coreResult', 'cladResult'] for k in keys: assert k in result.keys() keys = ['corePoint', 'longAxisLen', 'shortAxisLen'] for k in keys: assert k in result.get('coreResult', {}).keys() assert k in result.get('cladResult', {}).keys() assert isinstance(result['core'], tuple) assert isinstance(result['clad'], tuple) assert isinstance(result['cladResult']['shortPlot'], tuple) assert len(result['cladResult']['shortPlot']) == 2 assert isinstance(result['cladResult']['longPlot'], tuple) assert len(result['cladResult']['longPlot']) == 2 def test_class_octagon_getResult():
def _changeFiberType(self): key = str(self._view.fiberTypeBox.currentText()) SETTING().keyUpdates(key) newKey = SETTING().get('fiberType', 'error type') # self._view.fiberTypeLabel.setText(newKey) self._modelcv.updateClassifyObject(newKey)
#coding:utf-8 import logging from imgserver.myview import Controllers logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(__name__) from setting import config config.MODBUS_PORT = 'com14' import sys import os import pdb from setting.orderset import SETTING Set = SETTING("test", "octagon", "centerImg") Set['ifcamera'] = False from PyQt4.QtGui import QPalette, QColor, QApplication from PyQt4.QtCore import QCoreApplication, QFile from GUI.view.view import View from GUI.controller import Controller from util.load import loadStyleSheet if __name__ == '__main__': #测试台界面显示 # sys.stdout = open('setting\\abc.txt', 'w') print('len set', len(Set)) app = QApplication(sys.argv) app.setStyleSheet(loadStyleSheet('main')) pt = QPalette() #调色板 pt.setColor(QPalette.Background, QColor(4, 159, 241)) #界面背景色设置为蓝色
from setting.orderset import SETTING SETTING("") import SDK.MindPy as mdp from SDK.mdpy import GetRawImg import time import numpy as np def test_MindPy_pyd(): print dir(mdp) assert hasattr(mdp, "getCameraSerial") assert hasattr(mdp, "getRawImg") assert hasattr(mdp, "initCamera") assert hasattr(mdp, "uninitCamera") def test_init_release_camera(): try: get = GetRawImg() except ValueError as e: assert str(e)[-2:] == '16' else: get.unInitCamera() # time.sleep(0.3) try: get = GetRawImg() except ValueError as e: assert str(e)[-2:] == '16' else: get.unInitCamera()