工作随笔

写在前面的注意事项:sw_64(申威架构CPU)银河麒麟系统仅提供了一个Packages:https://update.cs2c.com.cn/NS/V10/V10SP1/os/adv/lic/base/sw_64/Packages/所以不用各种在去搜索别的没有用的了,官方给出的就是兼容好的最新Packages了。能使用官方包的一定要使用官方的包,不用自我发挥的要去浪费时间nginx麒麟官方给的是nginx1.16够用了mysql麒麟官方在申威(sw_64)下给提供的是mysql8.0够用了php麒麟官方在申威(sw_64)下给提供的是7.2.10,对于PHP项目来说这个版本明显还是差点,但是没有办法只能让程序去适配,不要幻想的去源码包编译之类的(或许可能有大佬能行)如果麒麟系统安装不完整的话,像yum、dnf这些命令完全使用不起来,如果yumsearch包名,明显可以搜出来,但是无法使用yuminstall包名直接重新安装麒麟系统就行了,不用各种修补了。【重要】注意只要动了配置文件就去重启一下相应的服务,尤其是mysqld.service、nginx.service、php-fpm.service随手常用的一些命令:防火墙的#安装防火墙yuminstallfirewalld#防火墙状态systemctlstatusfirewalld#启动防火墙systemctlenablefirewalld.servicesystemctlstartfirewalld.service#停止防火墙systemctlstopfirewalldsystemctldisablefirewalld端口占用情况#查看所有端口占用情况netstat-tuln#查看指定端口netstat-tuln|grep端口号#-tuln说明-t表示显示TCP端口-u表示显示UDP端口-l表示显示监听状态的端口-n表示直接使用数字形式显示地址和端口号mysql8.0远程访问问题:NavicatPremium12远程无法连接麒麟系统mysql8.0:解决:按如下步骤逐一排查校验-1、关闭本机windows的防火墙-2、ping一下麒麟服务器的IP地址是否畅通-3、关闭麒麟服务器的防火墙,或者将麒麟服务器的3306端口释放出来-4、查看3306端口是否ping通。打开cmd运行窗口,输入命令“telnetip地址3306”-5、检查麒麟服务器上的3306端口状态,使用命令netstat-anp|grep3306如果显示mysql3306前面的ip不是0.0.0.0,则需要修改掉;修改/etc/mysql/mysql.conf.d/mysqld.cnf将bind-address=127.0.0.1改为bind-address=0.0.0.0-6、开启mysql远程访问权限,允许远程连接麒麟系统上登入mysql,更改“mysql”数据库里的“user”表里的“host”项,将"localhost"改为"%mysql-uroot-p(输入root密码)USEmysql;updateusersetHost='%'whereUser='root';更改完毕后使用命令“flushprivilege”更新权限FLUSHPRIVILEGES;-7、Navicat连接mysql8.0:提示无法加载身份验证插件“caching_sha2_password”参考文档:https://blog.csdn.net/annita2019/article/details/132736944phpMyAdmin4.8.5无法运行问题:部署完phpmyadmin,访问主页报错:Errorduringsessionstart;pleasecheckyourPHPand/orwebserverlogfileandconfigureyourPHPinstallationproperly.Alsoensurethatcookiesareenabledinyourbrowser.解决:找到php.inc文件修改如下参数session.save_path="var/lib/php/session"问题:部署完phpmyadmin,root无法免密登录,如下修改:1、phpmyadmin根目录下的文件config.sample.inc.php$cfg['Servers'][$i]['AllowNoPassword']=true;(将false改成true),如果还是无法登录,就直接使用mysql的命令去给root设置个密码吧,别折腾了。2、使用mysql命令给root设置密码-登录到MySQL:mysql-uroot-选择MySQL数据库:USEmysql;-更新root用户的密码:ALTERUSER'root'@'localhost'IDENTIFIEDBY'新密码';-刷新权限:FLUSHPRIVILEGES;变更项目的PHP版本为7.2.10问题:修改本地windows电脑的ComposerPHP版本为7.2.10,并开启PHP中的相应扩展如curl、openssl等等:解决:修改系统的环境变量为php7.2.10,使用php-v查看,如果版本还没有切换过来,就直接重启电脑PHP7.2.10(cli)(built:Sep13201800:47:25)(NTSMSVC15(VisualC++2017)x64)Copyright(c)1997-2018ThePHPGroupZendEnginev3.2.0,Copyright(c)1998-2018ZendTechnologies问题:PHP版本要求不一致:Fatalerror:Composerdetectedissuesinyourplatform:YourComposerdependenciesrequireaPHPversion">=7.4.0".Youarerunning7.2.33.in/www/wwwroot/web/vendor/composer/platform_check.phponline24解决:删除项目内vendor,使用如下命令进行忽略平台的安装composerinstall--ignore-platform-reqs问题:删除或者更换依赖包不兼容PHP7.2.10的:解决:直接删除composerremove包名--ignore-platform-reqsPHP调试模式报错的处理问题:Undefinedvariable错误:解决:一般情况下php是不需要定义变量的,但如果服务器什么都报错的,就会出现错误。修改php.ini的配置在error_reporting设置:找到error_reporting=E_ALL修改为error_reporting=E_ALL&~E_NOTICE。在register_globals设置:找到register_globals=Off;修改为register_globals=On;Notice:Undefinedvariable:emailinD:\PHP7\ENOTE\ADDNOTE.PHPonline9。如果什么错误都不想让显示,直接修改:display_errors=Off如果你没有php.ini的修改权限,可在php头部加入ini_set("error_reporting","E_ALL&~E_NOTICE");即可。

Python学习笔记

问题一:ModuleNotFoundError:Nomodulenamed'libs.labelColor'再使用PPOCRLabel的时候一直在报错如下:Traceback(mostrecentcalllast):File"C:\Python310\lib\runpy.py",line196,in_run_module_as_mainreturn_run_code(code,main_globals,None,File"C:\Python310\lib\runpy.py",line86,in_run_codeexec(code,run_globals)File"C:\Python310\Scripts\PPOCRLabel.exe__main__.py",line4,infromPPOCRLabel.PPOCRLabelimportmainFile"C:\Python310\lib\site-packages\PPOCRLabel\PPOCRLabel.py",line43,infromlibs.labelColorimportlabel_colormapModuleNotFoundError:Nomodulenamed'libs.labelColor'后来才发现是因为同时安装了另外一个标注包labelimgPlus,随后将labelimgPlus进行卸载,即可问题二:使用标注工具进行标注的时候出现闪退情况如下所示:Traceback(mostrecentcalllast):File"C:\Python310\lib\site-packages\PPOCRLabel\libs\canvas.py",line596,inpaintEventp.drawRect(leftTop.x(),leftTop.y(),rectWidth,rectHeight)TypeError:argumentsdidnotmatchanyoverloadedcall:drawRect(self,rect:QRectF):argument1hasunexpectedtype'float'drawRect(self,x:int,y:int,w:int,h:int):argument1hasunexpectedtype'float'drawRect(self,r:QRect):argument1hasunexpectedtype'float'QBackingStore::endPaint()calledwithactivepainter;didyouforgettodestroyitorcallQPainter::end()onit?QPainter::begin:Painteralreadyactive修改文件canvas.py和shape.py问题三:显示box编号的时候出现闪退如下所示:Traceback(mostrecentcalllast):File"C:\Python310\lib\site-packages\PPOCRLabel\libs\canvas.py",line578,inpaintEventshape.paint(p)File"C:\Python310\lib\site-packages\PPOCRLabel\libs\shape.py",line186,inpaintpainter.drawText(min_x,min_y,text)TypeError:argumentsdidnotmatchanyoverloadedcall:drawText(self,p:Union[QPointF,QPoint],s:Optional[str]):argument1hasunexpectedtype'float'drawText(self,rectangle:QRectF,flags:int,text:Optional[str]):argument1hasunexpectedtype'float'drawText(self,rectangle:QRect,flags:int,text:Optional[str]):argument1hasunexpectedtype'float'drawText(self,rectangle:QRectF,text:Optional[str],option:QTextOption=QTextOption()):argument1hasunexpectedtype'float'drawText(self,p:QPoint,s:Optional[str]):argument1hasunexpectedtype'float'drawText(self,x:int,y:int,width:int,height:int,flags:int,text:Optional[str]):argument1hasunexpectedtype'float'drawText(self,x:int,y:int,s:Optional[str]):argument1hasunexpectedtype'float'QBackingStore::endPaint()calledwithactivepainter;didyouforgettodestroyitorcallQPainter::end()onit?最后附上修改过代码的两个文件的,直接替换就行了,替换目录如下:C:\Python310\lib\site-packages\PPOCRLabel\libs\```python#Copyright(c)<2015-Present>Tzutalin#Copyright(C)2013MIT,ComputerScienceandArtificialIntelligenceLaboratory.BryanRussell,AntonioTorralba,#WilliamT.Freeman.Permissionisherebygranted,freeofcharge,toanypersonobtainingacopyofthissoftwareand#associateddocumentationfiles(the"Software"),todealintheSoftwarewithoutrestriction,includingwithout#limitationtherightstouse,copy,modify,merge,publish,distribute,sublicense,and/orsellcopiesofthe#Software,andtopermitpersonstowhomtheSoftwareisfurnishedtodoso,subjecttothefollowingconditions:#Theabovecopyrightnoticeandthispermissionnoticeshallbeincludedinallcopiesorsubstantialportionsof#theSoftware.THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSORIMPLIED,INCLUDINGBUT#NOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENT#SHALLTHEAUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHERLIABILITY,WHETHERINANACTIONOF#CONTRACT,TORTOROTHERWISE,ARISINGFROM,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN#THESOFTWARE.importcopyfromPyQt5.QtCoreimportQt,pyqtSignal,QPointF,QPointfromPyQt5.QtGuiimportQPainter,QBrush,QColor,QPixmapfromPyQt5.QtWidgetsimportQWidget,QMenu,QApplicationfromlibs.shapeimportShapefromlibs.utilsimportdistanceCURSOR_DEFAULT=Qt.ArrowCursorCURSOR_POINT=Qt.PointingHandCursorCURSOR_DRAW=Qt.CrossCursorCURSOR_MOVE=Qt.ClosedHandCursorCURSOR_GRAB=Qt.OpenHandCursorclassCanvas(QWidget):zoomRequest=pyqtSignal(int)scrollRequest=pyqtSignal(int,int)newShape=pyqtSignal()#selectionChanged=pyqtSignal(bool)selectionChanged=pyqtSignal(list)shapeMoved=pyqtSignal()drawingPolygon=pyqtSignal(bool)CREATE,EDIT=list(range(2))_fill_drawing=False#drawshadowsepsilon=5.0def__init__(self,*args,**kwargs):super(Canvas,self).__init__(*args,**kwargs)#Initialiselocalstate.self.mode=self.EDITself.shapes=[]self.shapesBackups=[]self.current=Noneself.selectedShapes=[]self.selectedShape=None#savetheselectedshapehereself.selectedShapesCopy=[]self.drawingLineColor=QColor(0,0,255)self.drawingRectColor=QColor(0,0,255)self.line=Shape(line_color=self.drawingLineColor)self.prevPoint=QPointF()self.offsets=QPointF(),QPointF()self.scale=1.0self.pixmap=QPixmap()self.visible={}self._hideBackround=Falseself.hideBackround=Falseself.hShape=Noneself.hVertex=Noneself._painter=QPainter()self._cursor=CURSOR_DEFAULT#Menus:self.menus=(QMenu(),QMenu())#Setwidgetoptions.self.setMouseTracking(True)self.setFocusPolicy(Qt.WheelFocus)self.verified=Falseself.drawSquare=Falseself.fourpoint=True#ADDself.pointnum=0self.movingShape=Falseself.selectCountShape=False#initialisationforpanningself.pan_initial_pos=QPoint()#lockedshapesrelatedself.lockedShapes=[]self.isInTheSameImage=FalsedefsetDrawingColor(self,qColor):self.drawingLineColor=qColorself.drawingRectColor=qColordefenterEvent(self,ev):self.overrideCursor(self._cursor)defleaveEvent(self,ev):self.restoreCursor()deffocusOutEvent(self,ev):self.restoreCursor()defisVisible(self,shape):returnself.visible.get(shape,True)defdrawing(self):returnself.mode==self.CREATEdefediting(self):returnself.mode==self.EDITdefsetEditing(self,value=True):self.mode=self.EDITifvalueelseself.CREATEifnotvalue:#Createself.unHighlight()self.deSelectShape()self.prevPoint=QPointF()self.repaint()defunHighlight(self):ifself.hShape:self.hShape.highlightClear()self.hVertex=self.hShape=NonedefselectedVertex(self):returnself.hVertexisnotNonedefmouseMoveEvent(self,ev):"""Updatelinewithlastpointandcurrentcoordinates."""pos=self.transformPos(ev.pos())#Updatecoordinatesinstatusbarifimageisopenedwindow=self.parent().window()ifwindow.filePathisnotNone:self.parent().window().labelCoordinates.setText('X:%d;Y:%d'%(pos.x(),pos.y()))#Polygondrawing.ifself.drawing():self.overrideCursor(CURSOR_DRAW)#?ifself.current:#DisplayannotationwidthandheightwhiledrawingcurrentWidth=abs(self.current[0].x()-pos.x())currentHeight=abs(self.current[0].y()-pos.y())self.parent().window().labelCoordinates.setText('Width:%d,Height:%d/X:%d;Y:%d'%(currentWidth,currentHeight,pos.x(),pos.y()))color=self.drawingLineColorifself.outOfPixmap(pos):#Don'tallowtheusertodrawoutsidethepixmap.#Clipthecoordinatesto0ormax,#iftheyareoutsidetherange[0,max]size=self.pixmap.size()clipped_x=min(max(0,pos.x()),size.width())clipped_y=min(max(0,pos.y()),size.height())pos=QPointF(clipped_x,clipped_y)eliflen(self.current)>1andself.closeEnough(pos,self.current[0]):#Attractlinetostartingpointandcolorisetoalertthe#user:pos=self.current[0]color=self.current.line_colorself.overrideCursor(CURSOR_POINT)self.current.highlightVertex(0,Shape.NEAR_VERTEX)ifself.drawSquare:self.line.points=[self.current[0],pos]self.line.close()elifself.fourpoint:self.line[0]=self.current[-1]self.line[1]=poselse:self.line[1]=pos#posisthemouse'scurrentpositionself.line.line_color=colorself.prevPoint=QPointF()#?self.current.highlightClear()else:self.prevPoint=posself.repaint()return#Polygoncopymoving.ifQt.RightButton&ev.buttons():ifself.selectedShapesCopyandself.prevPoint:self.overrideCursor(CURSOR_MOVE)self.boundedMoveShape(self.selectedShapesCopy,pos)self.repaint()elifself.selectedShapes:self.selectedShapesCopy=[s.copy()forsinself.selectedShapes]self.repaint()return#Polygon/Vertexmoving.ifQt.LeftButton&ev.buttons():ifself.selectedVertex():self.boundedMoveVertex(pos)self.shapeMoved.emit()self.repaint()self.movingShape=Trueelifself.selectedShapesandself.prevPoint:self.overrideCursor(CURSOR_MOVE)self.boundedMoveShape(self.selectedShapes,pos)self.shapeMoved.emit()self.repaint()self.movingShape=Trueelse:#pandelta_x=pos.x()-self.pan_initial_pos.x()delta_y=pos.y()-self.pan_initial_pos.y()self.scrollRequest.emit(delta_x,Qt.Horizontal)self.scrollRequest.emit(delta_y,Qt.Vertical)self.update()return#Justhoveringoverthecanvas,2posibilities:#-Highlightshapes#-Highlightvertex#Updateshape/vertexfillandtooltipvalueaccordingly.self.setToolTip("Image")forshapeinreversed([sforsinself.shapesifself.isVisible(s)]):#Lookforanearbyvertextohighlight.Ifthatfails,#checkifwehappentobeinsideashape.index=shape.nearestVertex(pos,self.epsilon)ifindexisnotNone:ifself.selectedVertex():self.hShape.highlightClear()self.hVertex,self.hShape=index,shapeshape.highlightVertex(index,shape.MOVE_VERTEX)self.overrideCursor(CURSOR_POINT)self.setToolTip("Click&dragtomovepoint")self.setStatusTip(self.toolTip())self.update()breakelifshape.containsPoint(pos):ifself.selectedVertex():self.hShape.highlightClear()self.hVertex,self.hShape=None,shapeself.setToolTip("Click&dragtomoveshape'%s'"%shape.label)self.setStatusTip(self.toolTip())self.overrideCursor(CURSOR_GRAB)self.update()breakelse:#Nothingfound,clearhighlights,resetstate.ifself.hShape:self.hShape.highlightClear()self.update()self.hVertex,self.hShape=None,Noneself.overrideCursor(CURSOR_DEFAULT)defmousePressEvent(self,ev):pos=self.transformPos(ev.pos())ifev.button()==Qt.LeftButton:ifself.drawing():#self.handleDrawing(pos)#OLDifself.current:ifself.fourpoint:#ADDIF#Addpointtoexistingshape.#print('AddingpointsinmousePressEventis',self.line[1])self.current.addPoint(self.line[1])self.line[0]=self.current[-1]ifself.current.isClosed():#print('1111')self.finalise()elifself.drawSquare:assertlen(self.current.points)==1self.current.points=self.line.pointsself.finalise()elifnotself.outOfPixmap(pos):#Createnewshape.self.current=Shape()self.current.addPoint(pos)self.line.points=[pos,pos]self.setHiding()self.drawingPolygon.emit(True)self.update()else:group_mode=int(ev.modifiers())==Qt.ControlModifierself.selectShapePoint(pos,multiple_selection_mode=group_mode)self.prevPoint=posself.pan_initial_pos=poselifev.button()==Qt.RightButtonandself.editing():group_mode=int(ev.modifiers())==Qt.ControlModifierself.selectShapePoint(pos,multiple_selection_mode=group_mode)self.prevPoint=posself.update()defmouseReleaseEvent(self,ev):ifev.button()==Qt.RightButton:menu=self.menus[bool(self.selectedShapesCopy)]self.restoreCursor()ifnotmenu.exec_(self.mapToGlobal(ev.pos()))\andself.selectedShapesCopy:#Cancelthemovebydeletingtheshadowcopy.#self.selectedShapeCopy=Noneself.selectedShapesCopy=[]self.repaint()elifev.button()==Qt.LeftButtonandself.selectedShapes:ifself.selectedVertex():self.overrideCursor(CURSOR_POINT)else:self.overrideCursor(CURSOR_GRAB)elifev.button()==Qt.LeftButtonandnotself.fourpoint:pos=self.transformPos(ev.pos())ifself.drawing():self.handleDrawing(pos)else:#panQApplication.restoreOverrideCursor()#?ifself.movingShapeandself.hShape:ifself.hShapeinself.shapes:index=self.shapes.index(self.hShape)if(self.shapesBackups[-1][index].points!=self.shapes[index].points):self.storeShapes()self.shapeMoved.emit()#connecttoupdateBoxlistinPPOCRLabel.pyself.movingShape=FalsedefendMove(self,copy=False):assertself.selectedShapesandself.selectedShapesCopyassertlen(self.selectedShapesCopy)==len(self.selectedShapes)ifcopy:fori,shapeinenumerate(self.selectedShapesCopy):shape.idx=len(self.shapes)#addcurrentboxindexself.shapes.append(shape)self.selectedShapes[i].selected=Falseself.selectedShapes[i]=shapeelse:fori,shapeinenumerate(self.selectedShapesCopy):self.selectedShapes[i].points=shape.pointsself.selectedShapesCopy=[]self.repaint()self.storeShapes()returnTruedefhideBackroundShapes(self,value):self.hideBackround=valueifself.selectedShapes:#Onlyhideothershapesifthereisacurrentselection.#Otherwisetheuserwillnotbeabletoselectashape.self.setHiding(True)self.repaint()defhandleDrawing(self,pos):ifself.currentandself.current.reachMaxPoints()isFalse:ifself.fourpoint:targetPos=self.line[self.pointnum]self.current.addPoint(targetPos)print('currentpointsinhandleDrawingis',self.line[self.pointnum])self.update()ifself.pointnum==3:self.finalise()else:initPos=self.current[0]print('initPos',self.current[0])minX=initPos.x()minY=initPos.y()targetPos=self.line[1]maxX=targetPos.x()maxY=targetPos.y()self.current.addPoint(QPointF(maxX,minY))self.current.addPoint(targetPos)self.current.addPoint(QPointF(minX,maxY))self.finalise()elifnotself.outOfPixmap(pos):print('release')self.current=Shape()self.current.addPoint(pos)self.line.points=[pos,pos]self.setHiding()self.drawingPolygon.emit(True)self.update()defsetHiding(self,enable=True):self._hideBackround=self.hideBackroundifenableelseFalsedefcanCloseShape(self):returnself.drawing()andself.currentandlen(self.current)>2defmouseDoubleClickEvent(self,ev):#Weneedatleast4pointshere,sincethemousePresshandler#addsanextraonebeforethishandleriscalled.ifself.canCloseShape()andlen(self.current)>3:ifnotself.fourpoint:self.current.popPoint()self.finalise()defselectShapes(self,shapes):forsinshapes:s.seleted=Trueself.setHiding()self.selectionChanged.emit(shapes)self.update()defselectShapePoint(self,point,multiple_selection_mode):"""Selectthefirstshapecreatedwhichcontainsthispoint."""ifself.selectedVertex():#Avertexismarkedforselection.index,shape=self.hVertex,self.hShapeshape.highlightVertex(index,shape.MOVE_VERTEX)returnself.hVertexelse:forshapeinreversed(self.shapes):ifself.isVisible(shape)andshape.containsPoint(point):self.calculateOffsets(shape,point)self.setHiding()ifmultiple_selection_mode:ifshapenotinself.selectedShapes:#listself.selectionChanged.emit(self.selectedShapes+[shape])else:self.selectionChanged.emit([shape])returnself.deSelectShape()defcalculateOffsets(self,shape,point):rect=shape.boundingRect()x1=rect.x()-point.x()y1=rect.y()-point.y()x2=(rect.x()+rect.width())-point.x()y2=(rect.y()+rect.height())-point.y()self.offsets=QPointF(x1,y1),QPointF(x2,y2)defsnapPointToCanvas(self,x,y):"""Movesapointx,ytowithintheboundariesofthecanvas.:return:(x,y,snapped)wheresnappedisTrueifxorywerechanged,Falseifnot."""ifx<0orx>self.pixmap.width()ory<0ory>self.pixmap.height():x=max(x,0)y=max(y,0)x=min(x,self.pixmap.width())y=min(y,self.pixmap.height())returnx,y,Truereturnx,y,FalsedefboundedMoveVertex(self,pos):index,shape=self.hVertex,self.hShapepoint=shape[index]ifself.outOfPixmap(pos):size=self.pixmap.size()clipped_x=min(max(0,pos.x()),size.width())clipped_y=min(max(0,pos.y()),size.height())pos=QPointF(clipped_x,clipped_y)ifself.drawSquare:opposite_point_index=(index+2)%4opposite_point=shape[opposite_point_index]min_size=min(abs(pos.x()-opposite_point.x()),abs(pos.y()-opposite_point.y()))directionX=-1ifpos.x()-opposite_point.x()<0else1directionY=-1ifpos.y()-opposite_point.y()<0else1shiftPos=QPointF(opposite_point.x()+directionX*min_size-point.x(),opposite_point.y()+directionY*min_size-point.y())else:shiftPos=pos-pointif[shape[0].x(),shape[0].y(),shape[2].x(),shape[2].y()]\==[shape[3].x(),shape[1].y(),shape[1].x(),shape[3].y()]:shape.moveVertexBy(index,shiftPos)lindex=(index+1)%4rindex=(index+3)%4lshift=Nonershift=Noneifindex%2==0:rshift=QPointF(shiftPos.x(),0)lshift=QPointF(0,shiftPos.y())else:lshift=QPointF(shiftPos.x(),0)rshift=QPointF(0,shiftPos.y())shape.moveVertexBy(rindex,rshift)shape.moveVertexBy(lindex,lshift)else:shape.moveVertexBy(index,shiftPos)defboundedMoveShape(self,shapes,pos):iftype(shapes).__name__!='list':shapes=[shapes]ifself.outOfPixmap(pos):returnFalse#Noneedtomoveo1=pos+self.offsets[0]ifself.outOfPixmap(o1):pos-=QPointF(min(0,o1.x()),min(0,o1.y()))o2=pos+self.offsets[1]ifself.outOfPixmap(o2):pos+=QPointF(min(0,self.pixmap.width()-o2.x()),min(0,self.pixmap.height()-o2.y()))#Thenextlinetracksthenewpositionofthecursor#relativetotheshape,butalsoresultsinmakingit#abit"shaky"whennearingtheborderandallowsitto#gooutsideoftheshape'sareaforsomereason.XXX#self.calculateOffsets(self.selectedShape,pos)dp=pos-self.prevPointifdp:forshapeinshapes:shape.moveBy(dp)shape.close()self.prevPoint=posreturnTruereturnFalsedefdeSelectShape(self):ifself.selectedShapes:forshapeinself.selectedShapes:shape.selected=Falseself.setHiding(False)self.selectionChanged.emit([])self.update()defdeleteSelected(self):deleted_shapes=[]ifself.selectedShapes:forshapeinself.selectedShapes:self.shapes.remove(shape)deleted_shapes.append(shape)self.storeShapes()self.selectedShapes=[]self.update()self.updateShapeIndex()returndeleted_shapesdefstoreShapes(self):shapesBackup=[]forshapeinself.shapes:shapesBackup.append(shape.copy())iflen(self.shapesBackups)>=10:self.shapesBackups=self.shapesBackups[-9:]self.shapesBackups.append(shapesBackup)defcopySelectedShape(self):ifself.selectedShapes:self.selectedShapesCopy=[s.copy()forsinself.selectedShapes]self.boundedShiftShapes(self.selectedShapesCopy)self.endMove(copy=True)returnself.selectedShapesdefboundedShiftShapes(self,shapes):#Trytomoveinonedirection,andifitfailsinanother.#Giveupifbothfail.forshapeinshapes:point=shape[0]offset=QPointF(5.0,5.0)self.calculateOffsets(shape,point)self.prevPoint=pointifnotself.boundedMoveShape(shape,point-offset):self.boundedMoveShape(shape,point+offset)defpaintEvent(self,event):ifnotself.pixmap:returnsuper(Canvas,self).paintEvent(event)p=self._painterp.begin(self)p.setRenderHint(QPainter.Antialiasing)p.setRenderHint(QPainter.HighQualityAntialiasing)p.setRenderHint(QPainter.SmoothPixmapTransform)p.scale(self.scale,self.scale)p.translate(self.offsetToCenter())p.drawPixmap(0,0,self.pixmap)Shape.scale=self.scaleforshapeinself.shapes:if(shape.selectedornotself._hideBackround)andself.isVisible(shape):shape.fill=shape.selectedorshape==self.hShapeshape.paint(p)ifself.current:self.current.paint(p)self.line.paint(p)ifself.selectedShapesCopy:forsinself.selectedShapesCopy:s.paint(p)#Paintrectifself.currentisnotNoneandlen(self.line)==2andnotself.fourpoint:#print('Drawingrect')leftTop=self.line[0]rightBottom=self.line[1]rectWidth=rightBottom.x()-leftTop.x()rectHeight=rightBottom.y()-leftTop.y()p.setPen(self.drawingRectColor)brush=QBrush(Qt.BDiagPattern)p.setBrush(brush)#p.drawRect(leftTop.x(),leftTop.y(),rectWidth,rectHeight)p.drawRect(int(leftTop.x()),int(leftTop.y()),int(rectWidth),int(rectHeight))#ADD:if(self.fillDrawing()andself.fourpointandself.currentisnotNoneandlen(self.current.points)>=2):print('paintevent')drawing_shape=self.current.copy()drawing_shape.addPoint(self.line[1])drawing_shape.fill=Truedrawing_shape.paint(p)ifself.drawing()andnotself.prevPoint.isNull()andnotself.outOfPixmap(self.prevPoint):p.setPen(QColor(0,0,0))p.drawLine(int(self.prevPoint.x()),0,int(self.prevPoint.x()),self.pixmap.height())p.drawLine(0,int(self.prevPoint.y()),self.pixmap.width(),int(self.prevPoint.y()))self.setAutoFillBackground(True)ifself.verified:pal=self.palette()pal.setColor(self.backgroundRole(),QColor(184,239,38,128))self.setPalette(pal)else:pal=self.palette()pal.setColor(self.backgroundRole(),QColor(232,232,232,255))self.setPalette(pal)#adaptiveBBOXlabel&indexfontsizeifself.pixmap:h,w=self.pixmap.size().height(),self.pixmap.size().width()fontszie=int(max(h,w)/48)forsinself.shapes:s.fontsize=fontsziep.end()deffillDrawing(self):returnself._fill_drawingdeftransformPos(self,point):"""Convertfromwidget-logicalcoordinatestopainter-logicalcoordinates."""returnpoint/self.scale-self.offsetToCenter()defoffsetToCenter(self):s=self.scalearea=super(Canvas,self).size()w,h=self.pixmap.width()*s,self.pixmap.height()*saw,ah=area.width(),area.height()x=(aw-w)/(2*s)ifaw>welse0y=(ah-h)/(2*s)ifah>helse0returnQPointF(x,y)defoutOfPixmap(self,p):w,h=self.pixmap.width(),self.pixmap.height()returnnot(0<=p.x()<=wand0<=p.y()<=h)deffinalise(self):assertself.currentifself.current.points[0]==self.current.points[-1]:#print('finalse')self.current=Noneself.drawingPolygon.emit(False)self.update()returnself.current.close()self.current.idx=len(self.shapes)#addcurrentboxindexself.shapes.append(self.current)self.current=Noneself.setHiding(False)self.newShape.emit()self.update()defcloseEnough(self,p1,p2):#d=distance(p1-p2)#m=(p1-p2).manhattanLength()#print"d%.2f,m%d,%.2f"%(d,m,d-m)returndistance(p1-p2)<self.epsilon#Thesetwo,alongwithacalltoadjustSizearerequiredforthe#scrollarea.defsizeHint(self):returnself.minimumSizeHint()defminimumSizeHint(self):ifself.pixmap:returnself.scale*self.pixmap.size()returnsuper(Canvas,self).minimumSizeHint()defwheelEvent(self,ev):qt_version=4ifhasattr(ev,"delta")else5ifqt_version==4:ifev.orientation()==Qt.Vertical:v_delta=ev.delta()h_delta=0else:h_delta=ev.delta()v_delta=0else:delta=ev.angleDelta()h_delta=delta.x()v_delta=delta.y()mods=ev.modifiers()ifQt.ControlModifier==int(mods)andv_delta:self.zoomRequest.emit(v_delta)else:v_deltaandself.scrollRequest.emit(v_delta,Qt.Vertical)h_deltaandself.scrollRequest.emit(h_delta,Qt.Horizontal)ev.accept()defkeyPressEvent(self,ev):key=ev.key()shapesBackup=copy.deepcopy(self.shapes)iflen(shapesBackup)==0:returnself.shapesBackups.pop()self.shapesBackups.append(shapesBackup)ifkey==Qt.Key_Escapeandself.current:print('ESCpress')self.current=Noneself.drawingPolygon.emit(False)self.update()elifkey==Qt.Key_Returnandself.canCloseShape():self.finalise()elifkey==Qt.Key_Leftandself.selectedShapes:self.moveOnePixel('Left')elifkey==Qt.Key_Rightandself.selectedShapes:self.moveOnePixel('Right')elifkey==Qt.Key_Upandself.selectedShapes:self.moveOnePixel('Up')elifkey==Qt.Key_Downandself.selectedShapes:self.moveOnePixel('Down')elifkey==Qt.Key_Xandself.selectedShapes:foriinrange(len(self.selectedShapes)):self.selectedShape=self.selectedShapes[i]ifself.rotateOutOfBound(0.01):continueself.selectedShape.rotate(0.01)self.shapeMoved.emit()self.update()elifkey==Qt.Key_Candself.selectedShapes:foriinrange(len(self.selectedShapes)):self.selectedShape=self.selectedShapes[i]ifself.rotateOutOfBound(-0.01):continueself.selectedShape.rotate(-0.01)self.shapeMoved.emit()self.update()defrotateOutOfBound(self,angle):forshapeinrange(len(self.selectedShapes)):self.selectedShape=self.selectedShapes[shape]fori,pinenumerate(self.selectedShape.points):ifself.outOfPixmap(self.selectedShape.rotatePoint(p,angle)):returnTruereturnFalsedefmoveOnePixel(self,direction):#print(self.selectedShape.points)self.selectCount=len(self.selectedShapes)self.selectCountShape=Trueforiinrange(len(self.selectedShapes)):self.selectedShape=self.selectedShapes[i]ifdirection=='Left'andnotself.moveOutOfBound(QPointF(-1.0,0)):#print("moveLeftonepixel")self.selectedShape.points[0]+=QPointF(-1.0,0)self.selectedShape.points[1]+=QPointF(-1.0,0)self.selectedShape.points[2]+=QPointF(-1.0,0)self.selectedShape.points[3]+=QPointF(-1.0,0)elifdirection=='Right'andnotself.moveOutOfBound(QPointF(1.0,0)):#print("moveRightonepixel")self.selectedShape.points[0]+=QPointF(1.0,0)self.selectedShape.points[1]+=QPointF(1.0,0)self.selectedShape.points[2]+=QPointF(1.0,0)self.selectedShape.points[3]+=QPointF(1.0,0)elifdirection=='Up'andnotself.moveOutOfBound(QPointF(0,-1.0)):#print("moveUponepixel")self.selectedShape.points[0]+=QPointF(0,-1.0)self.selectedShape.points[1]+=QPointF(0,-1.0)self.selectedShape.points[2]+=QPointF(0,-1.0)self.selectedShape.points[3]+=QPointF(0,-1.0)elifdirection=='Down'andnotself.moveOutOfBound(QPointF(0,1.0)):#print("moveDownonepixel")self.selectedShape.points[0]+=QPointF(0,1.0)self.selectedShape.points[1]+=QPointF(0,1.0)self.selectedShape.points[2]+=QPointF(0,1.0)self.selectedShape.points[3]+=QPointF(0,1.0)shapesBackup=[]shapesBackup=copy.deepcopy(self.shapes)self.shapesBackups.append(shapesBackup)self.shapeMoved.emit()self.repaint()defmoveOutOfBound(self,step):points=[p1+p2forp1,p2inzip(self.selectedShape.points,[step]*4)]returnTrueinmap(self.outOfPixmap,points)defsetLastLabel(self,text,line_color=None,fill_color=None,key_cls=None):asserttextself.shapes[-1].label=textifline_color:self.shapes[-1].line_color=line_coloriffill_color:self.shapes[-1].fill_color=fill_colorifkey_cls:self.shapes[-1].key_cls=key_clsself.storeShapes()returnself.shapes[-1]defundoLastLine(self):assertself.shapesself.current=self.shapes.pop()self.current.setOpen()self.line.points=[self.current[-1],self.current[0]]self.drawingPolygon.emit(True)defundoLastPoint(self):ifnotself.currentorself.current.isClosed():returnself.current.popPoint()iflen(self.current)>0:self.line[0]=self.current[-1]else:self.current=Noneself.drawingPolygon.emit(False)self.repaint()defresetAllLines(self):assertself.shapesself.current=self.shapes.pop()self.current.setOpen()self.line.points=[self.current[-1],self.current[0]]self.drawingPolygon.emit(True)self.current=Noneself.drawingPolygon.emit(False)self.update()defloadPixmap(self,pixmap):self.pixmap=pixmapself.shapes=[]self.repaint()defloadShapes(self,shapes,replace=True):ifreplace:self.shapes=list(shapes)else:self.shapes.extend(shapes)self.current=Noneself.hShape=Noneself.hVertex=None#self.hEdge=Noneself.storeShapes()self.updateShapeIndex()self.repaint()defsetShapeVisible(self,shape,value):self.visible[shape]=valueself.repaint()defcurrentCursor(self):cursor=QApplication.overrideCursor()ifcursorisnotNone:cursor=cursor.shape()returncursordefoverrideCursor(self,cursor):self._cursor=cursorifself.currentCursor()isNone:QApplication.setOverrideCursor(cursor)else:QApplication.changeOverrideCursor(cursor)defrestoreCursor(self):QApplication.restoreOverrideCursor()defresetState(self):self.restoreCursor()self.pixmap=Noneself.update()self.shapesBackups=[]defsetDrawingShapeToSquare(self,status):self.drawSquare=statusdefrestoreShape(self):ifnotself.isShapeRestorable:returnself.shapesBackups.pop()#latestshapesBackup=self.shapesBackups.pop()self.shapes=shapesBackupself.selectedShapes=[]forshapeinself.shapes:shape.selected=Falseself.updateShapeIndex()self.repaint()@propertydefisShapeRestorable(self):iflen(self.shapesBackups)<2:returnFalsereturnTruedefupdateShapeIndex(self):foriinrange(len(self.shapes)):self.shapes[i].idx=iself.update()#Copyright(c)<2015-Present>Tzutalin#Copyright(C)2013MIT,ComputerScienceandArtificialIntelligenceLaboratory.BryanRussell,AntonioTorralba,#WilliamT.Freeman.Permissionisherebygranted,freeofcharge,toanypersonobtainingacopyofthissoftwareand#associateddocumentationfiles(the"Software"),todealintheSoftwarewithoutrestriction,includingwithout#limitationtherightstouse,copy,modify,merge,publish,distribute,sublicense,and/orsellcopiesofthe#Software,andtopermitpersonstowhomtheSoftwareisfurnishedtodoso,subjecttothefollowingconditions:#Theabovecopyrightnoticeandthispermissionnoticeshallbeincludedinallcopiesorsubstantialportionsof#theSoftware.THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSORIMPLIED,INCLUDINGBUT#NOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY,FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENT#SHALLTHEAUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHERLIABILITY,WHETHERINANACTIONOF#CONTRACT,TORTOROTHERWISE,ARISINGFROM,OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN#THESOFTWARE.#!/usr/bin/python#-*-coding:utf-8-*-importmathimportsysfromPyQt5.QtCoreimportQPointFfromPyQt5.QtGuiimportQColor,QPen,QPainterPath,QFontfromlibs.utilsimportdistanceDEFAULT_LINE_COLOR=QColor(0,255,0,128)DEFAULT_FILL_COLOR=QColor(255,0,0,128)DEFAULT_SELECT_LINE_COLOR=QColor(255,255,255)DEFAULT_SELECT_FILL_COLOR=QColor(0,128,255,155)DEFAULT_VERTEX_FILL_COLOR=QColor(0,255,0,255)DEFAULT_HVERTEX_FILL_COLOR=QColor(255,0,0)DEFAULT_LOCK_COLOR=QColor(255,0,255)MIN_Y_LABEL=10classShape(object):P_SQUARE,P_ROUND=range(2)MOVE_VERTEX,NEAR_VERTEX=range(2)#Thefollowingclassvariablesinfluencethedrawing#of_all_shapeobjects.line_color=DEFAULT_LINE_COLORfill_color=DEFAULT_FILL_COLORselect_line_color=DEFAULT_SELECT_LINE_COLORselect_fill_color=DEFAULT_SELECT_FILL_COLORvertex_fill_color=DEFAULT_VERTEX_FILL_COLORhvertex_fill_color=DEFAULT_HVERTEX_FILL_COLORpoint_type=P_ROUNDpoint_size=8scale=1.0def__init__(self,label=None,line_color=None,difficult=False,key_cls="None",paintLabel=False,paintIdx=False):self.label=labelself.idx=None#bboxorder,onlyfortableannotationself.points=[]self.fill=Falseself.selected=Falseself.difficult=difficultself.key_cls=key_clsself.paintLabel=paintLabelself.paintIdx=paintIdxself.locked=Falseself.direction=0self.center=Noneself.epsilon=5#sameascanvasself._highlightIndex=Noneself._highlightMode=self.NEAR_VERTEXself._highlightSettings={self.NEAR_VERTEX:(4,self.P_ROUND),self.MOVE_VERTEX:(1.5,self.P_SQUARE),}self.fontsize=8self._closed=Falseifline_colorisnotNone:#Overridetheclassline_colorattribute#withanobjectattribute.Currentlythis#isusedfordrawingthependinglineadifferentcolor.self.line_color=line_colordefrotate(self,theta):fori,pinenumerate(self.points):self.points[i]=self.rotatePoint(p,theta)self.direction-=thetaself.direction=self.direction%(2*math.pi)defrotatePoint(self,p,theta):order=p-self.centercosTheta=math.cos(theta)sinTheta=math.sin(theta)pResx=cosTheta*order.x()+sinTheta*order.y()pResy=-sinTheta*order.x()+cosTheta*order.y()pRes=QPointF(self.center.x()+pResx,self.center.y()+pResy)returnpResdefclose(self):self.center=QPointF((self.points[0].x()+self.points[2].x())/2,(self.points[0].y()+self.points[2].y())/2)self._closed=TruedefreachMaxPoints(self):iflen(self.points)>=4:returnTruereturnFalsedefaddPoint(self,point):ifself.reachMaxPoints()andself.closeEnough(self.points[0],point):self.close()else:self.points.append(point)defcloseEnough(self,p1,p2):returndistance(p1-p2)<self.epsilondefpopPoint(self):ifself.points:returnself.points.pop()returnNonedefisClosed(self):returnself._closeddefsetOpen(self):self._closed=Falsedefpaint(self,painter):ifself.points:color=self.select_line_colorifself.selectedelseself.line_colorpen=QPen(color)#Tryusingintegersizesforsmootherdrawing(?)#pen.setWidth(max(1,int(round(2.0/self.scale))))painter.setPen(pen)line_path=QPainterPath()vrtx_path=QPainterPath()line_path.moveTo(self.points[0])#Uncommentingthefollowinglinewilldraw2paths#forthe1stvertex,andmakeitnon-filled,which#maybedesirable.#self.drawVertex(vrtx_path,0)fori,pinenumerate(self.points):line_path.lineTo(p)self.drawVertex(vrtx_path,i)ifself.isClosed():line_path.lineTo(self.points[0])painter.drawPath(line_path)painter.drawPath(vrtx_path)painter.fillPath(vrtx_path,self.vertex_fill_color)#Drawtextatthetop-leftifself.paintLabel:min_x=sys.maxsizemin_y=sys.maxsizeforpointinself.points:min_x=min(min_x,point.x())min_y=min(min_y,point.y())ifmin_x!=sys.maxsizeandmin_y!=sys.maxsize:font=QFont()font.setPointSize(self.fontsize)font.setBold(True)painter.setFont(font)ifself.labelisNone:self.label=""ifmin_y<MIN_Y_LABEL:min_y+=MIN_Y_LABEL#painter.drawText(min_x,min_y,self.label)painter.drawText(int(min_x),int(min_y),self.label)#Drawnumberatthetop-rightifself.paintIdx:min_x=sys.maxsizemin_y=sys.maxsizeforpointinself.points:min_x=min(min_x,point.x())min_y=min(min_y,point.y())ifmin_x!=sys.maxsizeandmin_y!=sys.maxsize:font=QFont()font.setPointSize(self.fontsize)font.setBold(True)painter.setFont(font)text=''ifself.idx!=None:text=str(self.idx)ifmin_y<MIN_Y_LABEL:min_y+=MIN_Y_LABEL#painter.drawText(min_x,min_y,text)painter.drawText(int(min_x),int(min_y),text)ifself.fill:color=self.select_fill_colorifself.selectedelseself.fill_colorpainter.fillPath(line_path,color)defdrawVertex(self,path,i):d=self.point_size/self.scaleshape=self.point_typepoint=self.points[i]ifi==self._highlightIndex:size,shape=self._highlightSettings[self._highlightMode]d*=sizeifself._highlightIndexisnotNone:self.vertex_fill_color=self.hvertex_fill_colorelse:self.vertex_fill_color=Shape.vertex_fill_colorifshape==self.P_SQUARE:path.addRect(point.x()-d/2,point.y()-d/2,d,d)elifshape==self.P_ROUND:path.addEllipse(point,d/2.0,d/2.0)else:assertFalse,"unsupportedvertexshape"defnearestVertex(self,point,epsilon):fori,pinenumerate(self.points):ifdistance(p-point)<=epsilon:returnireturnNonedefcontainsPoint(self,point):returnself.makePath().contains(point)defmakePath(self):path=QPainterPath(self.points[0])forpinself.points[1:]:path.lineTo(p)returnpathdefboundingRect(self):returnself.makePath().boundingRect()defmoveBy(self,offset):self.points=[p+offsetforpinself.points]defmoveVertexBy(self,i,offset):self.points[i]=self.points[i]+offsetdefhighlightVertex(self,i,action):self._highlightIndex=iself._highlightMode=actiondefhighlightClear(self):self._highlightIndex=Nonedefcopy(self):shape=Shape("%s"%self.label)shape.points=[pforpinself.points]shape.center=self.centershape.direction=self.directionshape.fill=self.fillshape.selected=self.selectedshape._closed=self._closedifself.line_color!=Shape.line_color:shape.line_color=self.line_colorifself.fill_color!=Shape.fill_color:shape.fill_color=self.fill_colorshape.difficult=self.difficultshape.key_cls=self.key_clsreturnshapedef__len__(self):returnlen(self.points)def__getitem__(self,key):returnself.points[key]def__setitem__(self,key,value):self.points[key]=value