def startVideoRecording(self,path,filename): self.open() self.videofilename = filename # make sure the path exists Environment.checkDir(path) self.videopath=path+self.videofilename return filename
def test_Histogram(self): histogram=PlotLib("Chessboard Colors",PlotLib.A4(turned=True)) for imageInfo in testEnv.imageInfos: cbWarped=testEnv.loadFromImageInfo(imageInfo) rgb=cv2.cvtColor(cbWarped.image,cv2.COLOR_BGR2RGB) histogram.addPlot(rgb,imageInfo.title) Environment.checkDir(Environment.debugImagePath) histogram.createHistogramPDF(Environment.debugImagePath+'chessboardColors',plotType=PlotType.HISTOGRAMM,infos={'Title': 'Chessboard Histogram'})
def showHistogramDebug(self, histograms, title, corners): """ 'show' the debug information for the given histograms by writing a plotted histogram image to the debugImagePath """ Environment.checkDir(Environment.debugImagePath) fig, axes = histograms[True].preparePlot(3, 2) histograms[True].plotRow(axes[0, 0], axes[0, 1]) histograms[False].plotRow(axes[1, 0], axes[1, 1]) histograms["background"].plotRow(axes[2, 0], axes[2, 1]) prefix = "histogram" filepath = Environment.debugImagePath + '%s-%s-%dx%d.jpg' % ( title, prefix, corners.rows, corners.cols) histograms[False].savefig(fig, filepath)
def test_Histogram(self): for imageInfo in testEnv.imageInfos: fen=imageInfo.fen if not fen==chess.STARTING_BOARD_FEN: continue image,video,warp=testEnv.prepareFromImageInfo(imageInfo) title=imageInfo.title #cbImage=ChessBoardImage(image,"chessboard") trapez=ChessTrapezoid(warp.pointList,rotation=warp.rotation,idealSize=800) cbWarped=trapez.warpedBoardImage(image) histogram=Histogram(cbWarped.image) histogram.showDebug() Environment.checkDir(Environment.debugImagePath) histogram.save(Environment.debugImagePath+title+"-histogram.jpg")
def photo(self, path): try: if self.videoAnalyzer.hasImageSet(): # make sure the path exists Environment.checkDir(path) video = self.videoAnalyzer.vision.video filename = 'chessboard_%s.jpg' % (video.fileTimeStamp()) video.writeImage(self.videoAnalyzer.cbImageSet.cbGUI.image, path + filename) msg = "still image <a href='/photo/%s'>%s</a> taken from input %s" % ( filename, filename, self.args.input) else: msg = "no imageset for photo available" return self.index(msg) except BaseException as e: return self.indexException(e)
def __init__(self, headless=None): ''' constructor ''' super().__init__() if headless is None: self.headless = Environment.inContinuousIntegration() else: self.headless = headless rlen = len(Environment4Test.rotations) wlen = len(Environment4Test.warpPointList) fenlen = len(Environment4Test.fens) if rlen != wlen: raise Exception("%d rotations for %d warpPoints" % (rlen, wlen)) if fenlen != wlen: raise Exception("%d FENs for %d images" % (fenlen, wlen)) self.imageInfos = [] for num in range(1, 1000): path = self.testMedia + "chessBoard%03d.jpg" % (num) if not os.path.isfile(path): break if num - 1 >= len(Environment4Test.rotations): raise Exception("%d test files for %d warpPoints/rotations" % (num, wlen)) imageInfo = ImageInfo( num, title="image%03d" % (num), path=path, fen=Environment4Test.fens[num - 1], rotation=Environment4Test.rotations[num - 1], warpPoints=Environment4Test.warpPointList[num - 1]) self.imageInfos.append(imageInfo)
def test_WebCamGames(self): # get the testEnvironment testEnv = Environment() for webCamGame in WebCamGame.getWebCamGames(testEnv.testMediaPath).values(): if debug: print (webCamGame.asJson()) webCamGame.save("testGames")
def __init__(self, args, logger=None): """ construct me """ self.args = args self.videoStream = None self.videoAnalyzer = VideoAnalyzer(args, logger=logger) self.videoAnalyzer.setUpDetector() self.board = self.videoAnalyzer.vision.board self.setDebug(args.debug) self.env = Environment()
def test_MovingBoard(self): ''' test moving a board and detecting the positions ''' video = testEnv.getVideo() testvideos = ['emptyBoard001', 'baxter'] expected = [51, 155] imagePath = Environment.debugImagePath + "testMovingBoard/" Environment.checkDir(imagePath) for testindex, testvideo in enumerate(testvideos): video.open(testEnv.testMedia + testvideo + ".avi") ret = True speedup = 5 frames = 0 found = 0 while ret: ret, image, quitWanted = video.readFrame(show=False) frames += 1 if quitWanted: break if ret: try: title = "corners-%s-%04d" % (testvideo, frames) startt = timer() finder = BoardFinder(image, video=video) corners = finder.findChessBoard(image, title) warped = video.warp(image.copy(), corners.trapez8x8) video.drawTrapezoid(image, corners.trapez8x8.tolist(), (255, 0, 0)) video.showImage(warped, "warped") endt = timer() video.writeImage(image, imagePath + title + ".jpg") video.writeImage(warped, imagePath + title + "-warped.jpg") found += 1 print("%3d/%3d: %dx%d in %.1f s" % (found, frames, corners.rows, corners.cols, (endt - startt))) except Exception as ex: print("%3d/%3d: %s" % (found, frames, ex)) if frames % speedup == 0: video.showImage(image, "original") video.close() assert found == expected[testindex]
def save(self, path="games"): env = Environment() savepath = str(env.projectPath) + "/" + path Environment.checkDir(savepath) savedir = savepath + "/" + self.gameid Environment.checkDir(savedir) jsonFile = savedir + "/" + self.gameid + "-webcamgame" self.writeJson(jsonFile) gameJsonFile = savedir + "/" + self.gameid self.writeJson(gameJsonFile) if self.locked is not None and not self.locked: if self.fen is not None: fenFile = savedir + "/" + self.gameid + ".fen" print(self.fen, file=open(fenFile, 'w')) if self.pgn is not None: pgnFile = savedir + "/" + self.gameid + ".pgn" # see https://python-chess.readthedocs.io/en/latest/pgn.html print(self.pgn, file=open(pgnFile, 'w'), end="\n\n") return savedir
def fromArgs(args): env = Environment() if args is None or args.game is None: webCamGame = WebCamGame.createNewGame() else: gamepath = args.game if not gamepath.startswith("/"): gamepath = env.games + "/" + gamepath webCamGame = WebCamGame.readJson(gamepath) if webCamGame is None: #self.videoAnalyzer.log("could not read %s " % (gamepath)) webCamGame = webCamGame.createNewGame() webCamGame.checkEnvironment(env) if args is not None: if args.event is not None: webCamGame.headers["Event"] = args.event if args.site is not None: webCamGame.headers["Site"] = args.site if args.round is not None: webCamGame.headers["Round"] = args.round if args.white is not None: webCamGame.headers["White"] = args.white if args.black is not None: webCamGame.headers["Black"] = args.black return webCamGame
def __init__(self, args, board=None): self.device = args.input self.title = Video.title(self.device) self.video = Video(self.title) self.video.headless = Environment.inContinuousIntegration() self.args = args self.showDebug = args.debug self.start = None self.quitWanted = False self.hasImage = False self.timestamps = [] self.debug = args.debug if board is None: board = Board(args=args) self.board = board if self.args.fen is not None: self.board.updatePieces(self.args.fen) self.warp = Warp(args.warpPointList) self.warp.rotation = args.rotation if self.args.nowarp: self.warp.warping = True self.firstFrame = True self.speedup = args.speedup pass
#!/usr/bin/python3 # part of https://github.com/WolfgangFahl/play-chess-with-a-webcam # Global imports from pcwawc.args import Args from pcwawc.environment import Environment from pcwawc.webapp import WebApp from flask import Flask, request from flask_autoindex import AutoIndex from flask_restful import Api import logging import platform import os.path import sys env = Environment() # prepare the RESTful application # prepare static webserver # set the project root directory as the static folder, you can set others. app = Flask(__name__, static_url_path='', static_folder=str(env.projectPath) + '/web') files_index = AutoIndex(app, browse_root=env.games, add_url_rules=False) api = Api(app) # app.logger.addHandler(logging.StreamHandler(STDOUT)) app.logger.setLevel(logging.INFO) if WebApp.debug: app.logger.setLevel(logging.DEBUG) app.logger.info("python src folder is %s" % (env.scriptPath))
def __init__(self,trapez): self.frames=0 self.trapez=trapez self.preMoveStats=None self.imagePath=Environment.debugImagePath+"states/" Environment.checkDir(self.imagePath)
def save(self, path="games/videos"): env = Environment() savepath = str(env.projectPath) + "/" + path Environment.checkDir(savepath) jsonFile = savepath + "/" + self.title self.writeJson(jsonFile)
def checkEnvironment(self, env): Environment.checkDir(env.games)
def getVideo(): video = Video() video.headless = Environment.inContinuousIntegration() return video
def writeDebug(self, image, title, prefix): Environment.checkDir(Environment.debugImagePath) cv2.imwrite( Environment.debugImagePath + '%s-%s-%dx%d.jpg' % (title, prefix, self.rows, self.cols), image)