def check_files(self): if not isfile(self.imgfile): print('{} not found'.format(self.imgfile)) return False if not isfile(self.jfile): print('{} not found'.format(self.jfile)) return False if not isfile(self.rawfile): print('{} not found'.format(self.rawfile)) return False if not isfile(self.ljson): print('{} not found'.format(self.ljson)) return False return True
def process_json(prefix): imgfont = cv2.FONT_HERSHEY_SIMPLEX orig_path = '../input_rs/' imgfile = orig_path + prefix + '_Color.png' rawfile = orig_path + prefix + '_Depth.raw' jfile = prefix + '_Color_keypoints.json' if not isfile(imgfile): print('{} not found'.format(imgfile)) return if not isfile(jfile): print('{} not found'.format(jfile)) return if not isfile(rawfile): print('{} not found'.format(rawfile)) return myctr = FindContour() myctr.load_file(imgfile, rawfile) p1 = () p2 = () json = read_jsonfile(jfile) kps = json['people'][0]['pose_keypoints_2d'] img = cv2.imread(imgfile) for idx, kpn in enumerate(KP): x = int(kps[idx * 3]) y = int(kps[idx * 3 + 1]) pos = (x, y) cv2.circle(img, pos, 3, color=(255, 255, 0)) imgtext = str(kpn).replace('KP.', '') #print('{}: {} - ({},{})'.format(idx, imgtext, x, y)) cv2.putText(img, imgtext, pos, imgfont, 0.8, (0, 0, 255), 2, cv2.LINE_AA) if idx == KP.RIGHT_SHOULDER.value: p1 = (x, y) if idx == KP.LEFT_SHOULDER.value: p2 = (x, y) #print('show #1') #cv2.imshow('img', img) #cv2.waitKey(0) #print('imshow from listpts.py') img2 = myctr.query_length(p1, p2, img=img) cv2.imshow('img', img2) cv2.waitKey(0)
def main(): '''main function''' WIN_NAME = 'foobar' cv2.namedWindow(WIN_NAME) cv2.moveWindow(WIN_NAME, 50, 50) if len(sys.argv) > 1: # has argument for ff in sys.argv[1:]: print('imread {}'.format(ff)) img = cv2.imread(ff) cv2.imshow(WIN_NAME, img) cv2.waitKey(0) else: setting_fn = 'setting.json' if not myutil.isfile(setting_fn): print('[ERROR] cannot find setting: {}'.format(setting_fn)) print('[INFO] may use argument') else: app_name = 'readim.py' data = myutil.read_setting(setting_fn) home = os.environ['HOME'] picpath = home + '/' + data[app_name]['path'] print(picpath) for img_file in data[app_name]['images']: pic1 = picpath + '/' + img_file print(pic1) if os.path.isfile(pic1): cv_test(pic1) else: print("file not found: {}".format(pic1)) #cv_drawline() cv2.destroyAllWindows()
def load_setting(self): ''' load setting ''' if not myutil.isfile(self.sett_json): print(f'[FAIL] setting file not found: {self.sett_json}') sett = myutil.read_jsonfile(self.sett_json) self.data_file_name = sett.get('data_file_name') self.resp_json = sett.get('resp_json')
def do_image(fn): print('read: {}'.format(fn)) if not myutil.isfile(fn): print("image {} not found...".format(fn)) exit(1) img = cv.imread(fn) #run_detect(img) run_detect_decode(img)
def append_path(fn): ''' append $HOME ''' home = os.environ.get('HOME') path = home + '/Private/' + fn if not isfile(path): print('[FAIL] key file not exist: {}'.format(path)) return None return path
def append_path(fn): ''' append $HOME ''' home = os.environ.get('HOME') path = home + '/Private/' + fn if not isfile(path): print(f'[FAIL] key file not exist: {path}') return None return path
def save_data(self, arr): ''' save array to data.txt ''' mode = 'wt' if myutil.isfile('data.txt'): #print('file exists, use "at"') mode = 'at' with open(self.data_file_name, mode, encoding='utf8') as datafile: for elem in arr: print(f'{elem}', file=datafile)
def load_setting(fn): if not myutil.isfile(fn): return None, None data = myutil.read_jsonfile(SETTING_FN) #print(data['fn']) fn = data.get('fn') print('image fn: {}'.format(fn)) frame = np.zeros((640, 480, 3), np.uint8) if myutil.isfile(fn): frame = cv2.imread(fn) else: print('image file not found: {}'.format(fn)) rect = data['rect'] rect = tuple(map(np.int16, rect)) print('preset loaded') return frame, rect
def get_randomorg_apikey(): ''' get apikey of random.org from json file ''' home = os.environ.get('HOME') keypath = home + '/' + 'Private/random-org.json' if not myutil.isfile(keypath): print('[FAIL] key file not exist: {}'.format(keypath)) return "" data = myutil.read_jsonfile(keypath) apiKey = data.get('apiKey') if apiKey is None: print('[WARN] apiKey is None') return "" return apiKey
def get_randomorg_apikey(): ''' get apikey of random.org from json file ''' home = os.environ.get('HOME') keypath = home + '/' + 'Private/random-org.json' if not myutil.isfile(keypath): print(f'[FAIL] key file not exist: {keypath}') return "" data = myutil.read_jsonfile(keypath) apiKey = data.get('apiKey') if apiKey is None: print('[WARN] apiKey is None') return "" return apiKey
def main(): '''main function''' # strData = translate_img_to_str('lena.jpg') # print strData ofn = 'out.jpg' if len(sys.argv) == 1: fn1 = 'img1.jpg' fn2 = 'img2.jpg' debug = False elif len(sys.argv) == 3: fn1 = sys.argv[1] fn2 = sys.argv[2] debug = True else: print('specify img1 img2...') return if isfile(fn1) and isfile(fn2): combine_two_images(ofn, fn1, fn2, debug) print('output to {}'.format(ofn)) else: print('{} and/or {} is not available'.format(fn1, fn2))
def read_setting(self): ''' read setting ''' if self.debug: print('read_setting()') home = os.getenv('HOME') self.jsonpath = home + '/Private/driving_data.json' if not myutil.isfile(self.jsonpath): print('setting file not found', self.jsonpath) sys.exit(1) self.jsondata = myutil.read_jsonfile(self.jsonpath) self.docid = self.jsondata.get('docid', '') self.sheetid = self.jsondata.get('sheetid', '') self.compose_url()
def main(): '''main function''' import sys # strData = translate_img_to_str('lena.jpg') # print strData ofn = 'out.jpg' if len(sys.argv) == 1: fn1 = 'img1.jpg' fn2 = 'img2.jpg' debug = False elif len(sys.argv) == 3: fn1 = sys.argv[1] fn2 = sys.argv[2] debug = True else: print('specify img1 img2...') return if isfile(fn1) and isfile(fn2): combine_two_images(ofn, fn1, fn2, debug) print('output to {}'.format(ofn)) else: print('{} and/or {} is not available'.format(fn1, fn2))
def main(): '''main function''' app_name = 'imgur.py' data = myutil.read_setting('setting.json') json_data = data[app_name]['picture'] title = 'deer' fn = 'deer.png' if myutil.isfile(fn): print('file {} already exists, will not download'.format(fn)) else: fn = try_to_download(json_data, title) im = Image.open(fn) im.show()
def get_apikey(self): ''' get apikey ''' keyfile = 'pushover-net.json' home = os.environ.get('HOME') keypath = home + '/Private/' + keyfile if not myutil.isfile(keypath): print('[FAIL] key file not exist: {}'.format(keypath)) return False data = myutil.read_jsonfile(keypath) if data is None: return False self.userkey = data.get('userkey') self.apitoken = data.get('apitoken') self._device = data.get('device') return True
def get_apikey(self): ''' get apikey ''' keyfile = 'pushover-net.json' home = os.environ.get('HOME') keypath = home + '/Private/' + keyfile if not myutil.isfile(keypath): print(f'[FAIL] key file not exist: {keypath}') return False data = myutil.read_jsonfile(keypath) if data is None: return False self.userkey = data.get('userkey') self.apitoken = data.get('apitoken') self._device = data.get('device') return True
def get_apikey(): ''' get api key ''' keyfile = 'pushover-net.json' userkey = None apitoken = None home = os.environ.get('HOME') keypath = home + '/Private/' + keyfile if not myutil.isfile(keypath): print('[FAIL] key file not exist: {}'.format(keypath)) return None, None data = myutil.read_jsonfile(keypath) if data is None: return None, None userkey = data.get('userkey') apitoken = data.get('apitoken') return userkey, apitoken
def test(fn): ''' test ''' data = myutil.read_jsonfile(fn) if data is None: print('[FAIL] read json fail') arr = data.get('result').get('random').get('data') cnt = 0 mode = 'wt' if myutil.isfile('data.txt'): print('file exists, use "at"') mode = 'at' with open('data.txt', mode, encoding='utf8') as datafile: for elem in arr: print(f'{elem}', file=datafile) cnt += 1 print(f'cnt: {cnt}')
def test(fn): ''' test ''' data = myutil.read_jsonfile(fn) if data is None: print('[FAIL] read json fail') arr = data.get('result').get('random').get('data') cnt = 0 mode = 'wt' if myutil.isfile('data.txt'): print('file exists, use "at"') mode = 'at' with open('data.txt', mode) as datafile: for elem in arr: print('{}'.format(elem), file=datafile) cnt += 1 print('cnt: {}'.format(cnt))
def get_apikey(): ''' get api key ''' keyfile = 'pushover-net.json' userkey = None apitoken = None home = os.environ.get('HOME') keypath = home + '/Private/' + keyfile if not myutil.isfile(keypath): print(f'[FAIL] key file not exist: {keypath}') return None, None data = myutil.read_jsonfile(keypath) if data is None: return None, None userkey = data.get('userkey') apitoken = data.get('apitoken') return userkey, apitoken
def main(): ''' main ''' jsonf = 'setting.json' data = myutil.read_jsonfile(jsonf) # use get() instead of 'operator []' to prevent exeception zfile = data.get('go.py').get('zipfile') if not myutil.isfile(zfile): print('specified file not found: %s' % zfile) return zf = zipfile.ZipFile(zfile, 'r') print('zipfile: {}\n{}'.format(zfile, '-' * 40)) flist = zf.namelist() for ff in flist: print(ff) zf.close()
def __init__(self): self.font = cv2.FONT_HERSHEY_SIMPLEX #self.tracker = dlib.correlation_tracker() #self.win = dlib.image_window() self.inited = False self.default_width = 640 self.default_height = 480 # dat download from: http://dlib.net/face_landmark_detection.py.html predictor_data = 'shape_predictor_68_face_landmarks.dat' if isfile(predictor_data): self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor(predictor_data) self.inited = True else: print('need predictor data file, use the following command to fetch data file') print('wget {}\n'.format(predictor_data)) return
def load_config(self, fn): data = myutil.read_jsonfile(fn, debug=True) #print(data['fn']) fn = data.get('fn') frame = np.zeros((640, 480, 3), np.uint8) if myutil.isfile(fn): frame = cv.imread(fn) else: print('file not found: {}'.format(fn)) return None rect = data['rect'] self.focal_length = self.calc_focallength(rect) rect = tuple(map(np.int16, rect)) print(rect) self.tracker.clear() self.tracker.add_target(frame, rect) print('preset loaded') return frame
def __init__(self): self.font = cv2.FONT_HERSHEY_SIMPLEX #self.tracker = dlib.correlation_tracker() #self.win = dlib.image_window() self.inited = False self.default_width = 640 self.default_height = 480 # dat download from: http://dlib.net/face_landmark_detection.py.html predictor_data = 'shape_predictor_68_face_landmarks.dat' if isfile(predictor_data): self.detector = dlib.get_frontal_face_detector() self.predictor = dlib.shape_predictor(predictor_data) self.inited = True else: print( 'need predictor data file, use the following command to fetch data file' ) print('wget {}\n'.format(predictor_data)) return
def _check(self): ''' check ''' if self.bodyfile: if not isfile(self.bodyfile): print('[ERROR] bodyfile not found:', self.bodyfile) sys.exit(1)
def _check(self): ''' check ''' if self.bodyfile: if not isfile(self.bodyfile): print('ggmail: specified but not found:', self.bodyfile) sys.exit(1)
def run(self): setting_fn = 'setting.json' if myutil.isfile(setting_fn): print('setting exists') self.load_setting(setting_fn) # load preset frame and rect if True and myutil.isfile('h**o.json'): print('preset exists') tmp_frame = self.load_config('h**o.json') #self.frame = tmp_frame print('test: {}'.format( self.distance_to_camera(self.KNOWN_WIDTH, self.focal_length, 135))) while True: playing = not self.paused and not self.rect_sel.dragging if playing or self.frame is None: ret, frame = self.cap.read() if not ret: break self.frame = frame.copy() self.auto_output_frame = frame.copy() w, h = getsize(self.frame) vis = np.zeros((h, w * 2, 3), np.uint8) # if tmp_frame: # vis[:,w:] = tmp_frame vis[:h, :w] = self.frame if len(self.tracker.targets) > 0: target = self.tracker.targets[0] vis[:, w:] = target.image draw_keypoints(vis[:, w:], target.keypoints) x0, y0, x1, y1 = target.rect cv.rectangle(vis, (x0 + w, y0), (x1 + w, y1), (0, 255, 0), 2) is_ok_to_export = False if playing: tracked = self.tracker.track(self.frame) if len(tracked) > 0: tracked = tracked[0] wtf = np.int32(tracked.quad) if self.check_wtf(wtf): self.draw_result(vis, wtf) cv.fillPoly(vis, [wtf], (255, 0, 0)) for (x0, y0), (x1, y1) in zip(np.int32(tracked.p0), np.int32(tracked.p1)): cv.line(vis, (x0 + w, y0), (x1, y1), (0, 255, 0)) is_ok_to_export = True if self.auto_save: self.draw_result(self.auto_output_frame, wtf) fn = 'autosave_{:04d}.png'.format(self.auto_serial) self.save_image(fn, self.auto_output_frame) self.auto_serial += 1 draw_keypoints(vis, self.tracker.frame_points) self.rect_sel.draw(vis) cv.imshow(WIN_NAME, vis) ch = cv.waitKey(1) if ch == ord(' '): self.paused = not self.paused elif ch == 27: break elif ch == ord('s'): fn = 'saved_{:04d}.png'.format(self.serial) self.serial += 1 self.save_image(fn, vis)
# -*- coding: utf-8 -*- ''' sample script to import cv2 and list where to load ''' import sys import cv2 from myutil import isfile, isdir, get_python_version print('python version: {}'.format(get_python_version())) print('opencv version: {}'.format(cv2.__version__)) for pp in sys.path: target = pp + '/cv2.so' #print('check {}'.format(target)) if isfile(target): print('found cv2.so at {}'.format(pp)) target = pp + '/cv2/' #print('check {}'.format(target)) if isdir(target): print('found cv2/ at {}'.format(pp))
def main(): # initialize the known distance from the camera to the object, which # preset distance from samples KNOWN_DISTANCE = 390 # initialize the known object width, which in this case, the piece of # paper, unit mm KNOWN_WIDTH = 252 KNOWN_HEIGHT = 201 # load the furst image that contains an object that is KNOWN TO BE 2 feet # from our camera, then find the paper marker in the image, and initialize # the focal length home = os.environ["HOME"] fn = home + '/Pictures/data/pic0001.png' if not myutil.isfile(fn): print('[ERROR] {} not found...'.format(fn)) exit(1) image = cv2.imread(fn) marker = find_marker(image) focalLength = (marker[1][0] * KNOWN_DISTANCE) / KNOWN_WIDTH draw_bounding_box(image, marker) print('output reference image to focal.png') cv2.imwrite('focal.png', image) #通过摄像头标定获取的像素焦距 #focalLength = 811.82 print('focalLength = ',focalLength) #return #打开摄像头 camera = cv2.VideoCapture(0) while camera.isOpened(): # get a frame (grabbed, frame) = camera.read() original = frame.copy() marker = find_marker(frame) if marker == 0: print(marker) continue dist = distance_to_camera(KNOWN_WIDTH, focalLength, marker[1][0]) draw_bounding_box(frame, marker) # inches 转换为 cm cv2.putText(frame, "%.2fmm" % dist, (40, frame.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 3) # show a frame cv2.imshow("capture", frame) key = cv2.waitKey(1) if key & 0xFF == ord('q') or key == 0x1B: break elif key & 0xFF == ord('s'): print('save result to result.png') cv2.imwrite('result.png', frame) cv2.imwrite('origin.png', original) camera.release() cv2.destroyAllWindows()