diff --git "a/Tools\345\267\245\345\205\267\345\214\205/OpenCV_Window_Management/opencv_windows_management.py" "b/Tools\345\267\245\345\205\267\345\214\205/OpenCV_Window_Management/opencv_windows_management.py" index 80a05fe0..00baf3d4 100644 --- "a/Tools\345\267\245\345\205\267\345\214\205/OpenCV_Window_Management/opencv_windows_management.py" +++ "b/Tools\345\267\245\345\205\267\345\214\205/OpenCV_Window_Management/opencv_windows_management.py" @@ -24,7 +24,7 @@ def __init__(self, name, image, weight=1): class opencv_windows_management: def __init__(self): - self.windows = dict() + self.windows = {} root = tk.Tk() screen_width = root.winfo_screenwidth() diff --git "a/ch04-\345\233\276\347\211\207/show_image.py" "b/ch04-\345\233\276\347\211\207/show_image.py" index 343882df..021ffa14 100644 --- "a/ch04-\345\233\276\347\211\207/show_image.py" +++ "b/ch04-\345\233\276\347\211\207/show_image.py" @@ -12,6 +12,7 @@ """ + import numpy as np import cv2, sys @@ -36,14 +37,9 @@ cv2.imshow(title, temp) k = cv2.waitKey(10) - if k == 27 or k == ord('q'): + if k in [27, ord('q')]: break - #TODO 分辨率太大,需要缩放 if k == ord('g'): - # t = temp == img - # if t.all(): - # if t.any(): - # if temp == img: if gray is False: temp = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = True diff --git "a/ch05-\350\247\206\351\242\221/5.VideoPlay.py" "b/ch05-\350\247\206\351\242\221/5.VideoPlay.py" index 53885f03..ae170534 100755 --- "a/ch05-\350\247\206\351\242\221/5.VideoPlay.py" +++ "b/ch05-\350\247\206\351\242\221/5.VideoPlay.py" @@ -24,7 +24,7 @@ frame_no = 121 cap.set(1, frame_no) # Where frame_no is the frame you want ret, frame = cap.read() # Read the frame -cv2.imshow('frame_no'+str(frame_no), frame) +cv2.imshow(f'frame_no{frame_no}', frame) FRAME_NOW = cap.get(cv2.CAP_PROP_POS_FRAMES) print('当前帧数', FRAME_NOW) # 当前帧数 122.0 diff --git "a/ch05-\350\247\206\351\242\221/5.VideoWriter.py" "b/ch05-\350\247\206\351\242\221/5.VideoWriter.py" index b2791ed9..f44de229 100755 --- "a/ch05-\350\247\206\351\242\221/5.VideoWriter.py" +++ "b/ch05-\350\247\206\351\242\221/5.VideoWriter.py" @@ -18,17 +18,15 @@ while cap.isOpened(): ret, frame = cap.read() - if ret is True: - - frame = cv2.resize(frame, (640, 480)) + if ret is not True: + break - # write the flipped frame - out.write(frame) + frame = cv2.resize(frame, (640, 480)) - cv2.imshow('frame', frame) + # write the flipped frame + out.write(frame) - else: - break + cv2.imshow('frame', frame) key = cv2.waitKey(1) if key == ord("q"): diff --git "a/ch05-\350\247\206\351\242\221/VideoCaptureOnePicture.py" "b/ch05-\350\247\206\351\242\221/VideoCaptureOnePicture.py" index 1a7b3bc9..d4a8fee3 100644 --- "a/ch05-\350\247\206\351\242\221/VideoCaptureOnePicture.py" +++ "b/ch05-\350\247\206\351\242\221/VideoCaptureOnePicture.py" @@ -29,7 +29,7 @@ def id_generator(size=6, chars=string.ascii_uppercase + string.digits): if key == ord("q"): break elif key == ord("s"): - cv2.imwrite(id_generator() + '.jpg', frame) + cv2.imwrite(f'{id_generator()}.jpg', frame) cap.release() cv2.destroyAllWindows() diff --git "a/ch06-\347\273\230\345\233\276\345\207\275\346\225\260/\347\224\273\345\234\206\345\234\210.py" "b/ch06-\347\273\230\345\233\276\345\207\275\346\225\260/\347\224\273\345\234\206\345\234\210.py" index fb6a53c6..9c843c66 100644 --- "a/ch06-\347\273\230\345\233\276\345\207\275\346\225\260/\347\224\273\345\234\206\345\234\210.py" +++ "b/ch06-\347\273\230\345\233\276\345\207\275\346\225\260/\347\224\273\345\234\206\345\234\210.py" @@ -32,7 +32,7 @@ def click_event(event, x, y, flags, param): canvas = np.zeros((300, 300, 3), dtype="uint8") while True: try: - for i in range(0, 25): + for _ in range(0, 25): radius = np.random.randint(5, high=200) color = np.random.randint(0, high=256, size=(3,)).tolist() pt = np.random.randint(0, high=300, size=(2,)) diff --git "a/ch07-\346\212\212\351\274\240\346\240\207\345\275\223\347\224\273\347\254\224/\351\274\240\346\240\207\345\267\246\345\217\263\351\224\256\345\233\236\350\260\203\345\207\275\346\225\260.py" "b/ch07-\346\212\212\351\274\240\346\240\207\345\275\223\347\224\273\347\254\224/\351\274\240\346\240\207\345\267\246\345\217\263\351\224\256\345\233\236\350\260\203\345\207\275\346\225\260.py" index 4c90a249..1bb15e43 100644 --- "a/ch07-\346\212\212\351\274\240\346\240\207\345\275\223\347\224\273\347\254\224/\351\274\240\346\240\207\345\267\246\345\217\263\351\224\256\345\233\236\350\260\203\345\207\275\346\225\260.py" +++ "b/ch07-\346\212\212\351\274\240\346\240\207\345\275\223\347\224\273\347\254\224/\351\274\240\346\240\207\345\267\246\345\217\263\351\224\256\345\233\236\350\260\203\345\207\275\346\225\260.py" @@ -21,7 +21,7 @@ def click_event(event, x, y, flags, param): green = img[y, x, 1] print(red, green, blue) - strRGB = str(red) + "," + str(green) + "," + str(blue) + strRGB = f"{str(red)},{str(green)},{str(blue)}" font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, strRGB, (x, y), font, 1, (255, 255, 255), 2) cv2.imshow('original', img) diff --git "a/ch08-\347\224\250\346\273\221\345\212\250\346\235\241\345\201\232\350\260\203\350\211\262\346\235\277/8.createTrackbar.py" "b/ch08-\347\224\250\346\273\221\345\212\250\346\235\241\345\201\232\350\260\203\350\211\262\346\235\277/8.createTrackbar.py" index 5edfcd40..8fea211d 100755 --- "a/ch08-\347\224\250\346\273\221\345\212\250\346\235\241\345\201\232\350\260\203\350\211\262\346\235\277/8.createTrackbar.py" +++ "b/ch08-\347\224\250\346\273\221\345\212\250\346\235\241\345\201\232\350\260\203\350\211\262\346\235\277/8.createTrackbar.py" @@ -30,11 +30,7 @@ def nothing(x): b = cv2.getTrackbarPos('B', 'image') s = cv2.getTrackbarPos(switch, 'image') # 另外一个重要应用就是用作转换按钮 - if s == 0: - img[:] = 0 - else: - img[:] = [b, g, r] - + img[:] = 0 if s == 0 else [b, g, r] cv2.imshow('image', img) k = cv2.waitKey(1) # & 0xFF if k == ord("q"): diff --git "a/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\2172.py" "b/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\2172.py" index 0fee7194..6010c8ee 100644 --- "a/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\2172.py" +++ "b/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\2172.py" @@ -8,6 +8,7 @@ 图像相减2.py: """ + import cv2 import numpy as np import matplotlib.pyplot as plt @@ -45,7 +46,7 @@ image, contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) -areas = list() +areas = [] for i, cnt in enumerate(contours): areas.append((i, cv2.contourArea(cnt))) diff --git "a/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\217_camera.py" "b/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\217_camera.py" index 432dbf4e..2a25592f 100644 --- "a/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\217_camera.py" +++ "b/ch10-\345\233\276\345\203\217\344\270\212\347\232\204\347\256\227\346\234\257\350\277\220\347\256\227/\345\233\276\345\203\217\347\233\270\345\207\217_camera.py" @@ -8,6 +8,7 @@ 图像相减_camera.py: """ + import cv2 import numpy as np @@ -49,7 +50,7 @@ # cap.set(1, frame_no)#第10帧 ret, bgimg0 = cap.read() # 背景 bgimg = cv2.cvtColor(bgimg0, cv2.COLOR_BGR2GRAY) -cv2.imshow('bgimg' + str(frame_no), bgimg0) +cv2.imshow(f'bgimg{frame_no}', bgimg0) # cv2.imwrite('desk_bgimg.jpg',bgimg) while cap.isOpened(): diff --git "a/ch20-\345\233\276\345\203\217\351\207\221\345\255\227\345\241\224/20.Apple_orange.py" "b/ch20-\345\233\276\345\203\217\351\207\221\345\255\227\345\241\224/20.Apple_orange.py" index 05b693fc..020528d1 100755 --- "a/ch20-\345\233\276\345\203\217\351\207\221\345\255\227\345\241\224/20.Apple_orange.py" +++ "b/ch20-\345\233\276\345\203\217\351\207\221\345\255\227\345\241\224/20.Apple_orange.py" @@ -11,6 +11,7 @@ 4. 在拉普拉斯的每一层 图像 合 苹果的左 与橘子的右 合 5. 根据 合后的图像 字塔 建原始图像。 ''' + import cv2 import numpy as np, sys @@ -20,14 +21,14 @@ # generate Gaussian pyramid for A G = A.copy() gpA = [G] -for i in range(6): +for _ in range(6): G = cv2.pyrDown(G) gpA.append(G) # generate Gaussian pyramid for B G = B.copy() gpB = [G] -for i in range(6): +for _ in range(6): G = cv2.pyrDown(G) gpB.append(G) diff --git a/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/aruco_test1.py b/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/aruco_test1.py index 90ede87e..4d68f2db 100644 --- a/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/aruco_test1.py +++ b/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/aruco_test1.py @@ -8,6 +8,7 @@ aruco11.py: """ + import time, cv2 # import cv2.aruco as A import numpy as np @@ -28,8 +29,7 @@ allCorners = [] allIds = [] decimator = 0 -for i in range(200): - +for _ in range(200): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) res = cv2.aruco.detectMarkers(gray, dictionary) diff --git a/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/calibrateCamera2.py b/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/calibrateCamera2.py index 1f5a020c..27974ca2 100644 --- a/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/calibrateCamera2.py +++ b/ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/calibrateCamera2.py @@ -27,8 +27,7 @@ def get_image(camera): def make_grayscale(img): - ret = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) - return ret + return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def main(): diff --git "a/ch21-\350\275\256\345\273\223Contours/draw\346\234\200\345\244\247\347\232\204\350\275\256\345\273\223.py" "b/ch21-\350\275\256\345\273\223Contours/draw\346\234\200\345\244\247\347\232\204\350\275\256\345\273\223.py" index 8c2503e9..0c932d87 100644 --- "a/ch21-\350\275\256\345\273\223Contours/draw\346\234\200\345\244\247\347\232\204\350\275\256\345\273\223.py" +++ "b/ch21-\350\275\256\345\273\223Contours/draw\346\234\200\345\244\247\347\232\204\350\275\256\345\273\223.py" @@ -8,6 +8,7 @@ draw最大的轮廓.py: """ + import cv2 import numpy as np @@ -22,10 +23,7 @@ image, contours, hierarchy = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) -areas = list() -for i, cnt in enumerate(contours): - areas.append((i, cv2.contourArea(cnt)))#面积大小 - +areas = [(i, cv2.contourArea(cnt)) for i, cnt in enumerate(contours)] # a2 = sorted(areas, key=lambda d: d[1], reverse=True)#按面积大小,从大到小排序 diff --git "a/ch22-\347\233\264\346\226\271\345\233\276/22.3-2D\347\233\264\346\226\271\345\233\276.py" "b/ch22-\347\233\264\346\226\271\345\233\276/22.3-2D\347\233\264\346\226\271\345\233\276.py" index 17faba8a..e23b3b4f 100644 --- "a/ch22-\347\233\264\346\226\271\345\233\276/22.3-2D\347\233\264\346\226\271\345\233\276.py" +++ "b/ch22-\347\233\264\346\226\271\345\233\276/22.3-2D\347\233\264\346\226\271\345\233\276.py" @@ -22,6 +22,7 @@ """ + import cv2 import numpy as np @@ -36,5 +37,3 @@ h, s, v = cv2.split(hsv) hist, xbins, ybins = np.histogram2d(h.ravel(), s.ravel(), [180, 256], [[0, 180], [0, 256]]) - -pass diff --git "a/ch22-\347\233\264\346\226\271\345\233\276/hist.py" "b/ch22-\347\233\264\346\226\271\345\233\276/hist.py" index 5e326c6a..84a7c1f9 100755 --- "a/ch22-\347\233\264\346\226\271\345\233\276/hist.py" +++ "b/ch22-\347\233\264\346\226\271\345\233\276/hist.py" @@ -33,8 +33,7 @@ def hist_curve(im): hist = np.int32(np.around(hist_item)) pts = np.int32(np.column_stack((bins, hist))) cv2.polylines(h, [pts], False, col) - y = np.flipud(h) - return y + return np.flipud(h) def hist_lines(im): diff --git "a/ch24-\346\250\241\346\235\277\345\214\271\351\205\215/24.1-OpenCV\344\270\255\347\232\204\346\250\241\346\235\277\345\214\271\351\205\215-matchTemplate.py" "b/ch24-\346\250\241\346\235\277\345\214\271\351\205\215/24.1-OpenCV\344\270\255\347\232\204\346\250\241\346\235\277\345\214\271\351\205\215-matchTemplate.py" index 7ea2e7ad..e2692911 100755 --- "a/ch24-\346\250\241\346\235\277\345\214\271\351\205\215/24.1-OpenCV\344\270\255\347\232\204\346\250\241\346\235\277\345\214\271\351\205\215-matchTemplate.py" +++ "b/ch24-\346\250\241\346\235\277\345\214\271\351\205\215/24.1-OpenCV\344\270\255\347\232\204\346\250\241\346\235\277\345\214\271\351\205\215-matchTemplate.py" @@ -53,5 +53,5 @@ plt.title('Matching Result'), plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(img, cmap='gray') plt.title('Detected Point'), plt.xticks([]), plt.yticks([]) - plt.suptitle('method: ' + meth) + plt.suptitle(f'method: {meth}') plt.show() diff --git "a/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_camera.py" "b/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_camera.py" index a5dfe1b1..8ea754cf 100644 --- "a/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_camera.py" +++ "b/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_camera.py" @@ -50,17 +50,16 @@ def draw_line_rectangle(frame, margin): if key == ord("q"): break if key == ord('s'): - cv2.imwrite(id_generator() + '.jpg', frame2) + cv2.imwrite(f'{id_generator()}.jpg', frame2) # Capture frame-by-frame ret, frame = cap.read() m = mse(cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY), cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) print('mse', m, '----\n') - if abs(m - tm) < 2: # 静止画面,不用重复计算 + if abs(m - tm) < 2: continue - else: - temp = frame.copy() - tm = m + temp = frame.copy() + tm = m # # print(margin,frame.shape[0] - margin, margin,frame.shape[1] - margin)#40 680 40 1240 frame2 = frame[margin:frame.shape[0] - margin, margin:frame.shape[1] - margin] # .copy() diff --git "a/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_chess.py" "b/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_chess.py" index e5b0bb23..9b906399 100644 --- "a/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_chess.py" +++ "b/ch26-Hough\345\234\206\347\216\257\345\217\230\346\215\242/HoughCircles_chess.py" @@ -15,14 +15,12 @@ def detect_weiqi(img): # 检测棋子的颜色 - txt = 'black' gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, threshold = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY) c = Counter(list(threshold.flatten())) print(c.most_common()) - if c.most_common()[0][0] != 0: - txt = 'white' + txt = 'white' if c.most_common()[0][0] != 0 else 'black' return txt, threshold diff --git "a/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.4-SIFT_match.py" "b/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.4-SIFT_match.py" index 48cc2b4e..37fa387b 100755 --- "a/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.4-SIFT_match.py" +++ "b/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.4-SIFT_match.py" @@ -25,15 +25,7 @@ bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2, k=2) -# Apply ratio test -# 比值测试,首先获取与 A距离最近的点 B (最近)和 C (次近), -# 只有当 B/C 小于阀值时(0.75)才被认为是匹配, -# 因为假设匹配是一一对应的,真正的匹配的理想距离为0 -good = [] -for m, n in matches: - if m.distance < 0.75 * n.distance: - good.append([m]) - +good = [[m] for m, n in matches if m.distance < 0.75 * n.distance] # cv2.drawMatchesKnn expects list of lists as matches. # img3 = np.ndarray([2, 2]) # img3 = cv2.drawMatchesKnn(img1, kp1, img2, kp2, good[:10], img3, flags=2) diff --git "a/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.5-FLANN\345\214\271\351\205\215\345\231\250.py" "b/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.5-FLANN\345\214\271\351\205\215\345\231\250.py" index b387a4c2..9c9a90da 100644 --- "a/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.5-FLANN\345\214\271\351\205\215\345\231\250.py" +++ "b/ch37-\347\211\271\345\276\201\345\214\271\351\205\215/37.5-FLANN\345\214\271\351\205\215\345\231\250.py" @@ -15,6 +15,7 @@ + import numpy as np import cv2 from matplotlib import pyplot as plt @@ -38,7 +39,7 @@ flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(des1, des2, k=2) # Need to draw only good matches, so create a mask -matchesMask = [[0, 0] for i in range(len(matches))] +matchesMask = [[0, 0] for _ in range(len(matches))] # ratio test as per Lowe's paper for i, (m, n) in enumerate(matches): diff --git "a/ch38-\344\275\277\347\224\250\347\211\271\345\276\201\345\214\271\351\205\215\345\222\214\345\215\225\345\272\224\346\200\247\346\237\245\346\211\276\345\257\271\350\261\241/findHomography.py" "b/ch38-\344\275\277\347\224\250\347\211\271\345\276\201\345\214\271\351\205\215\345\222\214\345\215\225\345\272\224\346\200\247\346\237\245\346\211\276\345\257\271\350\261\241/findHomography.py" index 0e4dc98a..87c96942 100644 --- "a/ch38-\344\275\277\347\224\250\347\211\271\345\276\201\345\214\271\351\205\215\345\222\214\345\215\225\345\272\224\346\200\247\346\237\245\346\211\276\345\257\271\350\261\241/findHomography.py" +++ "b/ch38-\344\275\277\347\224\250\347\211\271\345\276\201\345\214\271\351\205\215\345\222\214\345\215\225\345\272\224\346\200\247\346\237\245\346\211\276\345\257\271\350\261\241/findHomography.py" @@ -8,6 +8,7 @@ findHomography.py:联合使用特征提取和 calib3d 模块中的 findHomography 在复杂图像中查找已知对象 """ + import numpy as np import cv2 from matplotlib import pyplot as plt @@ -28,11 +29,7 @@ flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(des1, des2, k=2) -# store all the good matches as per Lowe's ratio test. -good = [] -for m, n in matches: - if m.distance < 0.7 * n.distance: - good.append(m) +good = [m for m, n in matches if m.distance < 0.7 * n.distance] ''' 现在我们 置只有存在 10 个以上匹 时才去查找目标 MIN_MATCH_COUNT=10 否则显示 告消息 现在匹 不 如果找到了 够的匹 我们 提取两幅图像中匹 点的坐标。把它们传 入到函数中 算 变换。一旦我们找到 3x3 的变换矩 就可以使用它将查 图像的四个 点 四个 变换到目标图像中去了。然后再绘制出来。 diff --git "a/ch43-\345\247\277\345\212\277\344\274\260\350\256\241/calib3d.py" "b/ch43-\345\247\277\345\212\277\344\274\260\350\256\241/calib3d.py" index 80580af3..456b32b4 100644 --- "a/ch43-\345\247\277\345\212\277\344\274\260\350\256\241/calib3d.py" +++ "b/ch43-\345\247\277\345\212\277\344\274\260\350\256\241/calib3d.py" @@ -72,7 +72,7 @@ def draw_cube(img, corners, imgpts): cv2.imshow('img', img) k = cv2.waitKey(0) & 0xFF if k == ord('s'): - cv2.imwrite(fname[:6] + '.png', img) + cv2.imwrite(f'{fname[:6]}.png', img) cv2.destroyAllWindows() #如果你对计算机图形学感兴趣的 为了增加图像的真实性 你可以使用 OpenGL 来渲染更复杂的图形。 下一个目标 \ No newline at end of file diff --git "a/ch44-\345\257\271\346\236\201\345\207\240\344\275\225/code.py" "b/ch44-\345\257\271\346\236\201\345\207\240\344\275\225/code.py" index 52cd560a..5db3f6f1 100644 --- "a/ch44-\345\257\271\346\236\201\345\207\240\344\275\225/code.py" +++ "b/ch44-\345\257\271\346\236\201\345\207\240\344\275\225/code.py" @@ -64,7 +64,7 @@ def drawlines(img1, img2, lines, pts1, pts2): pts1 = [] pts2 = [] # ratio test as per Lowe's paper -for i, (m, n) in enumerate(matches): +for m, n in matches: if m.distance < 0.8 * n.distance: good.append(m) pts2.append(kp2[m.trainIdx].pt) diff --git "a/ch47-\346\224\257\346\214\201\345\220\221\351\207\217\346\234\272/47.2-\344\275\277\347\224\250SVM\350\277\233\350\241\214-\346\211\213\345\206\231\346\225\260\346\215\256OCR.py" "b/ch47-\346\224\257\346\214\201\345\220\221\351\207\217\346\234\272/47.2-\344\275\277\347\224\250SVM\350\277\233\350\241\214-\346\211\213\345\206\231\346\225\260\346\215\256OCR.py" index 25011222..c2f00521 100644 --- "a/ch47-\346\224\257\346\214\201\345\220\221\351\207\217\346\234\272/47.2-\344\275\277\347\224\250SVM\350\277\233\350\241\214-\346\211\213\345\206\231\346\225\260\346\215\256OCR.py" +++ "b/ch47-\346\224\257\346\214\201\345\220\221\351\207\217\346\234\272/47.2-\344\275\277\347\224\250SVM\350\277\233\350\241\214-\346\211\213\345\206\231\346\225\260\346\215\256OCR.py" @@ -36,8 +36,7 @@ def hog(img): bin_cells = bins[:10, :10], bins[10:, :10], bins[:10, 10:], bins[10:, 10:] mag_cells = mag[:10, :10], mag[10:, :10], mag[:10, 10:], mag[10:, 10:] hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)] - hist = np.hstack(hists) # hist is a 64 bit vector - return hist + return np.hstack(hists) # 最后 和前 一样 我们将大图分割成小图。使用每个数字的前 250 个作 为训练数据 diff --git "a/ch48-K\345\200\274\350\201\232\347\261\273/48.2.3_\351\242\234\350\211\262\351\207\217\345\214\2262.py" "b/ch48-K\345\200\274\350\201\232\347\261\273/48.2.3_\351\242\234\350\211\262\351\207\217\345\214\2262.py" index 3207f088..26decb1e 100755 --- "a/ch48-K\345\200\274\350\201\232\347\261\273/48.2.3_\351\242\234\350\211\262\351\207\217\345\214\2262.py" +++ "b/ch48-K\345\200\274\350\201\232\347\261\273/48.2.3_\351\242\234\350\211\262\351\207\217\345\214\2262.py" @@ -8,6 +8,7 @@ 48.2.3_颜色量化.py: """ + # 色 化就是减少图片中 色数目的一个 程。为什么 减少图片中的 色呢 减少内存消耗 有些 备的 源有 只能显示很少的 色。在 种情 况下就 色 化。我们使用 K 值聚类的方法来 色 化。 # 没有什么新的知 介绍了。现在有 3 个特征 R G B。所以我们 把图片数据变形成 Mx3 M 是图片中像素点的数目 的向 。聚类完成后 我们用聚类中心值替换与其同组的像素值 样结果图片就只含有指定数目的 色了。下 是代码 # -*- coding: utf-8 -*- @@ -39,7 +40,7 @@ a1.append([0,0,0]) a2=np.array(a1) a3=a2.reshape((img.shape)) - cv2.imshow('res2'+str(y), a3) + cv2.imshow(f'res2{str(y)}', a3) #最大的色块 diff --git "a/ch49-\350\256\241\347\256\227\346\221\204\345\275\261\345\255\246-\345\233\276\345\203\217\345\216\273\345\231\252/2-fastNlMeansDenoisingMulti.py" "b/ch49-\350\256\241\347\256\227\346\221\204\345\275\261\345\255\246-\345\233\276\345\203\217\345\216\273\345\231\252/2-fastNlMeansDenoisingMulti.py" index 9d4ba005..9875c4f0 100644 --- "a/ch49-\350\256\241\347\256\227\346\221\204\345\275\261\345\255\246-\345\233\276\345\203\217\345\216\273\345\231\252/2-fastNlMeansDenoisingMulti.py" +++ "b/ch49-\350\256\241\347\256\227\346\221\204\345\275\261\345\255\246-\345\233\276\345\203\217\345\216\273\345\231\252/2-fastNlMeansDenoisingMulti.py" @@ -8,13 +8,14 @@ 2-fastNlMeansDenoisingMulti.py: """ + import numpy as np import cv2 from matplotlib import pyplot as plt cap = cv2.VideoCapture('../data/vtest.avi') # create a list of first 5 frames -img = [cap.read()[1] for i in range(5)] +img = [cap.read()[1] for _ in range(5)] # convert all to grayscale gray = [cv2.cvtColor(i, cv2.COLOR_BGR2GRAY) for i in img] # convert all to float64 diff --git "a/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection1.py" "b/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection1.py" index 2da3c87f..899663b7 100644 --- "a/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection1.py" +++ "b/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection1.py" @@ -14,6 +14,7 @@ python Pedestrian_Detection1.py --images images """ + # import the necessary packages from __future__ import print_function from imutils.object_detection import non_max_suppression @@ -60,8 +61,9 @@ # show some information on the number of bounding boxes filename = imagePath[imagePath.rfind("/") + 1:] - print("[INFO] {}: {} original boxes, {} after suppression".format( - filename, len(rects), len(pick))) + print( + f"[INFO] {filename}: {len(rects)} original boxes, {len(pick)} after suppression" + ) # show the output images cv2.imshow("Before NMS", orig) diff --git "a/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection_video.py" "b/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection_video.py" index a1eb0b0d..d75a89ed 100644 --- "a/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection_video.py" +++ "b/ch51-\345\257\271\350\261\241\346\243\200\346\265\213-\344\275\277\347\224\250Haar\345\210\206\347\261\273\345\231\250\350\277\233\350\241\214\351\235\242\351\203\250\346\243\200\346\265\213/\350\241\214\344\272\272\346\243\200\346\265\213/Pedestrian_Detection_video.py" @@ -12,6 +12,7 @@ """ + # import the necessary packages from __future__ import print_function from imutils.object_detection import non_max_suppression @@ -89,7 +90,7 @@ # show some information on the number of bounding boxes # filename = imagePath[imagePath.rfind("/") + 1:] # print("[INFO] {}: {} original boxes, {} after suppression".format( - print("[INFO] {} original boxes, {} after suppression".format(len(rects), len(pick))) + print(f"[INFO] {len(rects)} original boxes, {len(pick)} after suppression") # show the output images cv2.imshow("Before NMS", orig) diff --git a/cv-Tkinter-GUI/photoboothapp.py b/cv-Tkinter-GUI/photoboothapp.py index 6e1cbe5e..3d00fe93 100644 --- a/cv-Tkinter-GUI/photoboothapp.py +++ b/cv-Tkinter-GUI/photoboothapp.py @@ -90,12 +90,12 @@ def takeSnapshot(self): # grab the current timestamp and use it to construct the # output path ts = datetime.datetime.now() - filename = "{}.jpg".format(ts.strftime("%Y-%m-%d_%H-%M-%S")) + filename = f'{ts.strftime("%Y-%m-%d_%H-%M-%S")}.jpg' p = os.path.sep.join((self.outputPath, filename)) # save the file cv2.imwrite(p, self.frame.copy()) - print("[INFO] saved {}".format(filename)) + print(f"[INFO] saved {filename}") def onClose(self): # set the stop event, cleanup the camera, and allow the rest of diff --git "a/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/pytesseract/ocr.py" "b/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/pytesseract/ocr.py" index 5dff89d0..09c725ab 100644 --- "a/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/pytesseract/ocr.py" +++ "b/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/pytesseract/ocr.py" @@ -8,6 +8,7 @@ ocr.py: """ + # import the necessary packages from PIL import Image import pytesseract @@ -40,7 +41,7 @@ # write the grayscale image to disk as a temporary file so we can # apply OCR to it -filename = "{}.png".format(os.getpid()) +filename = f"{os.getpid()}.png" cv2.imwrite(filename, gray) # load the image as a PIL/Pillow image, apply OCR, and then delete diff --git "a/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/tesserocr/GetComponentImages-example.py" "b/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/tesserocr/GetComponentImages-example.py" index eae1e0d7..c42b4b27 100644 --- "a/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/tesserocr/GetComponentImages-example.py" +++ "b/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/Tessract-OCR/tesserocr/GetComponentImages-example.py" @@ -8,6 +8,7 @@ GetComponentImages-example.py: """ + from PIL import Image from tesserocr import PyTessBaseAPI, RIL @@ -18,7 +19,7 @@ api.SetImage(image) boxes = api.GetComponentImages(RIL.TEXTLINE, True) - print('Found {} textline image components.'.format(len(boxes))) + print(f'Found {len(boxes)} textline image components.') for i, (im, box, _, _) in enumerate(boxes): # im is a PIL image object # box is a dict with x, y, w and h keys diff --git "a/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/\344\275\277\347\224\250-\346\250\241\346\235\277\345\214\271\351\205\215-\350\257\206\345\210\253\344\277\241\347\224\250\345\215\241\345\217\267\347\240\201/matchTemplate_credit_card_num1.py" "b/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/\344\275\277\347\224\250-\346\250\241\346\235\277\345\214\271\351\205\215-\350\257\206\345\210\253\344\277\241\347\224\250\345\215\241\345\217\267\347\240\201/matchTemplate_credit_card_num1.py" index f5d6dc63..e528aa3a 100644 --- "a/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/\344\275\277\347\224\250-\346\250\241\346\235\277\345\214\271\351\205\215-\350\257\206\345\210\253\344\277\241\347\224\250\345\215\241\345\217\267\347\240\201/matchTemplate_credit_card_num1.py" +++ "b/my01-OCR\346\226\207\345\255\227\350\257\206\345\210\253/\344\275\277\347\224\250-\346\250\241\346\235\277\345\214\271\351\205\215-\350\257\206\345\210\253\344\277\241\347\224\250\345\215\241\345\217\267\347\240\201/matchTemplate_credit_card_num1.py" @@ -22,6 +22,7 @@ """ + # import the necessary packages from imutils import contours import numpy as np @@ -148,7 +149,7 @@ locs = [] # loop over the contours -for (i, c) in enumerate(cnts): +for c in cnts: # compute the bounding box of the contour, then use the # bounding box coordinates to derive the aspect ratio (x, y, w, h) = cv2.boundingRect(c) @@ -204,7 +205,7 @@ scores = [] # loop over the reference digit name and digit ROI - for (digit, digitROI) in digits.items(): + for digitROI in digits.values(): # apply correlation-based template matching, take the # score, and update the scores list result = cv2.matchTemplate(roi, digitROI, @@ -224,7 +225,7 @@ output.extend(groupOutput) # display the output credit card information to the screen -print("Credit Card Type: {}".format(FIRST_NUMBER.get(output[0], 'None'))) -print("Credit Card #: {}".format("".join(output))) +print(f"Credit Card Type: {FIRST_NUMBER.get(output[0], 'None')}") +print(f'Credit Card #: {"".join(output)}') cv2.imshow("Image", image) # TODO 效果不是很好,需要改进 cv2.waitKey(0) diff --git "a/my02-\350\247\206\351\242\221-\345\257\271\350\261\241\350\267\237\350\270\252/tracker.py" "b/my02-\350\247\206\351\242\221-\345\257\271\350\261\241\350\267\237\350\270\252/tracker.py" index 88c3b505..6ea925ae 100644 --- "a/my02-\350\247\206\351\242\221-\345\257\271\350\261\241\350\267\237\350\270\252/tracker.py" +++ "b/my02-\350\247\206\351\242\221-\345\257\271\350\261\241\350\267\237\350\270\252/tracker.py" @@ -5,6 +5,7 @@ ''' + import cv2 import sys @@ -67,10 +68,26 @@ cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2) # Display tracker type on frame - cv2.putText(frame, tracker_type + " Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2) + cv2.putText( + frame, + f"{tracker_type} Tracker", + (100, 20), + cv2.FONT_HERSHEY_SIMPLEX, + 0.75, + (50, 170, 50), + 2, + ) # Display FPS on frame - cv2.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2) + cv2.putText( + frame, + f"FPS : {int(fps)}", + (100, 50), + cv2.FONT_HERSHEY_SIMPLEX, + 0.75, + (50, 170, 50), + 2, + ) # Display result cv2.imshow("Tracking", frame) diff --git "a/my03-\351\235\242\345\220\221\345\257\271\350\261\241/\346\243\200\346\265\213\347\272\277\346\235\241\345\222\214\345\275\242\347\212\266-\345\207\240\344\275\225\345\275\242\347\212\266.py" "b/my03-\351\235\242\345\220\221\345\257\271\350\261\241/\346\243\200\346\265\213\347\272\277\346\235\241\345\222\214\345\275\242\347\212\266-\345\207\240\344\275\225\345\275\242\347\212\266.py" index d8f3fd02..8cc42dfb 100644 --- "a/my03-\351\235\242\345\220\221\345\257\271\350\261\241/\346\243\200\346\265\213\347\272\277\346\235\241\345\222\214\345\275\242\347\212\266-\345\207\240\344\275\225\345\275\242\347\212\266.py" +++ "b/my03-\351\235\242\345\220\221\345\257\271\350\261\241/\346\243\200\346\265\213\347\272\277\346\235\241\345\222\214\345\275\242\347\212\266-\345\207\240\344\275\225\345\275\242\347\212\266.py" @@ -29,7 +29,7 @@ def save(self, image=None, filename_override=None): filename = "output/" + self.filename.split('/')[-1] if filename_override: - filename = "output/" + filename_override + filename = f"output/{filename_override}" return cv2.imwrite(filename, image) diff --git "a/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/extract_single_letters_from_captchas.py" "b/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/extract_single_letters_from_captchas.py" index 78f2530c..601339f0 100644 --- "a/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/extract_single_letters_from_captchas.py" +++ "b/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/extract_single_letters_from_captchas.py" @@ -15,7 +15,7 @@ # loop over the image paths for (i, captcha_image_file) in enumerate(captcha_image_files): - print("[INFO] processing image {}/{}".format(i + 1, len(captcha_image_files))) + print(f"[INFO] processing image {i + 1}/{len(captcha_image_files)}") # Since the filename contains the captcha text (i.e. "2A2X.png" has the text "2A2X"), # grab the base filename as the text @@ -52,8 +52,9 @@ # This contour is too wide to be a single letter! # Split it in half into two letter regions! half_width = int(w / 2) - letter_image_regions.append((x, y, half_width, h)) - letter_image_regions.append((x + half_width, y, half_width, h)) + letter_image_regions.extend( + ((x, y, half_width, h), (x + half_width, y, half_width, h)) + ) else: # This is a normal letter by itself letter_image_regions.append((x, y, w, h)) @@ -85,7 +86,7 @@ # write the letter image to a file count = counts.get(letter_text, 1) - p = os.path.join(save_path, "{}.png".format(str(count).zfill(6))) + p = os.path.join(save_path, f"{str(count).zfill(6)}.png") cv2.imwrite(p, letter_image) # increment the count for the current key diff --git "a/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/solve_captchas_with_model.py" "b/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/solve_captchas_with_model.py" index 97a947bf..c68d57bd 100644 --- "a/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/solve_captchas_with_model.py" +++ "b/my06-\351\252\214\350\257\201\347\240\201\350\257\206\345\210\253/solving_captchas_code_examples/solve_captchas_with_model.py" @@ -57,8 +57,9 @@ # This contour is too wide to be a single letter! # Split it in half into two letter regions! half_width = int(w / 2) - letter_image_regions.append((x, y, half_width, h)) - letter_image_regions.append((x + half_width, y, half_width, h)) + letter_image_regions.extend( + ((x, y, half_width, h), (x + half_width, y, half_width, h)) + ) else: # This is a normal letter by itself letter_image_regions.append((x, y, w, h)) @@ -105,7 +106,7 @@ # Print the captcha's text captcha_text = "".join(predictions) - print("CAPTCHA text is: {}".format(captcha_text)) + print(f"CAPTCHA text is: {captcha_text}") # Show the annotated image cv2.imshow("Output", output) diff --git "a/my08-opencv\347\216\251\346\270\270\346\210\217game/\350\277\236\350\277\236\347\234\213/compare_photos.py" "b/my08-opencv\347\216\251\346\270\270\346\210\217game/\350\277\236\350\277\236\347\234\213/compare_photos.py" index 14199e4a..ab139ac3 100644 --- "a/my08-opencv\347\216\251\346\270\270\346\210\217game/\350\277\236\350\277\236\347\234\213/compare_photos.py" +++ "b/my08-opencv\347\216\251\346\270\270\346\210\217game/\350\277\236\350\277\236\347\234\213/compare_photos.py" @@ -27,9 +27,7 @@ def get_image_difference(image_1, image_2): # 这个函数不行 img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0] img_template_diff = 1 - img_template_probability_match - # taking only 10% of histogram diff, since it's less accurate than template method - commutative_image_diff = (img_hist_diff / 10) + img_template_diff - return commutative_image_diff + return (img_hist_diff / 10) + img_template_diff def compare(i, j, img): diff --git "a/my10-\350\257\206\345\210\253\344\272\214\347\273\264\347\240\201/QR_Scaner1.py" "b/my10-\350\257\206\345\210\253\344\272\214\347\273\264\347\240\201/QR_Scaner1.py" index 0302b65b..7165856b 100644 --- "a/my10-\350\257\206\345\210\253\344\272\214\347\273\264\347\240\201/QR_Scaner1.py" +++ "b/my10-\350\257\206\345\210\253\344\272\214\347\273\264\347\240\201/QR_Scaner1.py" @@ -42,12 +42,12 @@ def main(): barcodeType = barcode.type # draw the barcode data and barcode type on the image - text = "{} ({})".format(barcodeData, barcodeType) + text = f"{barcodeData} ({barcodeType})" cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) # print the barcode type and data to the terminal - print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData)) + print(f"[INFO] Found {barcodeType} barcode: {barcodeData}") # show the output image cv2.imshow("Image", image) diff --git "a/\345\256\230\346\226\271samples/_coverage.py" "b/\345\256\230\346\226\271samples/_coverage.py" index 5ec3e18a..f4cd1831 100755 --- "a/\345\256\230\346\226\271samples/_coverage.py" +++ "b/\345\256\230\346\226\271samples/_coverage.py" @@ -4,6 +4,7 @@ Utility for measuring python opencv API coverage by samples. ''' + # Python 2/3 compatibility from __future__ import print_function @@ -12,7 +13,9 @@ import re if __name__ == '__main__': - cv2_callable = set(['cv2.'+name for name in dir(cv2) if callable( getattr(cv2, name) )]) + cv2_callable = { + f'cv2.{name}' for name in dir(cv2) if callable(getattr(cv2, name)) + } found = set() for fn in glob('*.py'): diff --git "a/\345\256\230\346\226\271samples/asift.py" "b/\345\256\230\346\226\271samples/asift.py" index ec74930c..dfc56773 100755 --- "a/\345\256\230\346\226\271samples/asift.py" +++ "b/\345\256\230\346\226\271samples/asift.py" @@ -93,11 +93,7 @@ def f(p): return keypoints, descrs keypoints, descrs = [], [] - if pool is None: - ires = it.imap(f, params) - else: - ires = pool.imap(f, params) - + ires = it.imap(f, params) if pool is None else pool.imap(f, params) for i, (k, d) in enumerate(ires): print('affine sampling: %d / %d\r' % (i+1, len(params)), end='') keypoints.extend(k) diff --git "a/\345\256\230\346\226\271samples/calibrate.py" "b/\345\256\230\346\226\271samples/calibrate.py" index 00dfe57f..54a7c2eb 100755 --- "a/\345\256\230\346\226\271samples/calibrate.py" +++ "b/\345\256\230\346\226\271samples/calibrate.py" @@ -13,6 +13,7 @@ defaults to ../data/left*.jpg ''' + # Python 2/3 compatibility from __future__ import print_function @@ -34,11 +35,7 @@ args = dict(args) args.setdefault('--debug', './output/') args.setdefault('--square_size', 1.0) - if not img_mask: - img_mask = '../data/left*.jpg' # default - else: - img_mask = img_mask[0] - + img_mask = '../data/left*.jpg' if not img_mask else img_mask[0] img_names = glob(img_mask) debug_dir = args.get('--debug') if not os.path.isdir(debug_dir): @@ -55,7 +52,7 @@ h, w = 0, 0 img_names_undistort = [] for fn in img_names: - print('processing %s... ' % fn, end='') + print(f'processing {fn}... ', end='') img = cv2.imread(fn, 0) if img is None: print("Failed to load", fn) @@ -105,8 +102,8 @@ # crop and save the image x, y, w, h = roi dst = dst[y:y+h, x:x+w] - outfile = img_found + '_undistorted.png' - print('Undistorted image written to: %s' % outfile) + outfile = f'{img_found}_undistorted.png' + print(f'Undistorted image written to: {outfile}') cv2.imwrite(outfile, dst) cv2.destroyAllWindows() diff --git "a/\345\256\230\346\226\271samples/common.py" "b/\345\256\230\346\226\271samples/common.py" index 09159bbe..bd03528b 100755 --- "a/\345\256\230\346\226\271samples/common.py" +++ "b/\345\256\230\346\226\271samples/common.py" @@ -54,10 +54,7 @@ def rect2rect_mtx(src, dst): src, dst = to_rect(src), to_rect(dst) cx, cy = (dst[1] - dst[0]) / (src[1] - src[0]) tx, ty = dst[0] - src[0] * (cx, cy) - M = np.float64([[ cx, 0, tx], - [ 0, cy, ty], - [ 0, 0, 1]]) - return M + return np.float64([[cx, 0, tx], [0, cy, ty], [0, 0, 1]]) def lookat(eye, target, up = (0, 0, 1)): @@ -202,11 +199,11 @@ def dragging(self): def grouper(n, iterable, fillvalue=None): '''grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx''' args = [iter(iterable)] * n - if PY3: - output = it.zip_longest(fillvalue=fillvalue, *args) - else: - output = it.izip_longest(fillvalue=fillvalue, *args) - return output + return ( + it.zip_longest(fillvalue=fillvalue, *args) + if PY3 + else it.izip_longest(fillvalue=fillvalue, *args) + ) def mosaic(w, imgs): '''Make a grid from images. @@ -215,10 +212,7 @@ def mosaic(w, imgs): imgs -- images (must have same size and format) ''' imgs = iter(imgs) - if PY3: - img0 = next(imgs) - else: - img0 = imgs.next() + img0 = next(imgs) if PY3 else imgs.next() pad = np.zeros_like(img0) imgs = it.chain([img0], imgs) rows = grouper(w, imgs, pad) diff --git "a/\345\256\230\346\226\271samples/deconvolution.py" "b/\345\256\230\346\226\271samples/deconvolution.py" index 74f51a71..3c0f6112 100755 --- "a/\345\256\230\346\226\271samples/deconvolution.py" +++ "b/\345\256\230\346\226\271samples/deconvolution.py" @@ -95,10 +95,7 @@ def update(_): d = cv2.getTrackbarPos('d', win) noise = 10**(-0.1*cv2.getTrackbarPos('SNR (db)', win)) - if defocus: - psf = defocus_kernel(d) - else: - psf = motion_kernel(ang, d) + psf = defocus_kernel(d) if defocus else motion_kernel(ang, d) cv2.imshow('psf', psf) psf /= psf.sum() diff --git "a/\345\256\230\346\226\271samples/demo.py" "b/\345\256\230\346\226\271samples/demo.py" index 81c6a859..99db0c03 100755 --- "a/\345\256\230\346\226\271samples/demo.py" +++ "b/\345\256\230\346\226\271samples/demo.py" @@ -60,9 +60,8 @@ def _click(self, event): proc = self.links[tag] if callable(proc): proc() - else: - if self.url_callback: - self.url_callback(proc) + elif self.url_callback: + self.url_callback(proc) class App: def __init__(self): @@ -158,7 +157,7 @@ def match_text(self, pattern, tag_proc, regexp=True): match_index = text.search(pattern, 'matchPos', count=count, regexp=regexp, stopindex='end') if not match_index: break - end_index = text.index( "%s+%sc" % (match_index, count.get()) ) + end_index = text.index(f"{match_index}+{count.get()}c") text.mark_set('matchPos', end_index) if callable(tag_proc): tag_proc(match_index, end_index, text.get(match_index, end_index)) @@ -168,7 +167,7 @@ def match_text(self, pattern, tag_proc, regexp=True): def on_run(self, *args): cmd = self.cmd_entry.get() print('running:', cmd) - Popen(sys.executable + ' ' + cmd, shell=True) + Popen(f'{sys.executable} {cmd}', shell=True) def run(self): tk.mainloop() diff --git "a/\345\256\230\346\226\271samples/dft.py" "b/\345\256\230\346\226\271samples/dft.py" index 4437aad6..eee361ea 100755 --- "a/\345\256\230\346\226\271samples/dft.py" +++ "b/\345\256\230\346\226\271samples/dft.py" @@ -31,11 +31,7 @@ def shift_dft(src, dst=None): elif src.dtype != dst.dtype: raise TypeError("src and dst must have equal types") - if src is dst: - ret = np.empty(src.shape, src.dtype) - else: - ret = dst - + ret = np.empty(src.shape, src.dtype) if src is dst else dst h, w = src.shape[:2] cx1 = cx2 = w/2 diff --git "a/\345\256\230\346\226\271samples/digits.py" "b/\345\256\230\346\226\271samples/digits.py" index 16d76a13..9d76a964 100755 --- "a/\345\256\230\346\226\271samples/digits.py" +++ "b/\345\256\230\346\226\271samples/digits.py" @@ -54,7 +54,7 @@ def split2d(img, cell_size, flatten=True): return cells def load_digits(fn): - print('loading "%s" ...' % fn) + print(f'loading "{fn}" ...') digits_img = cv2.imread(fn, 0) digits = split2d(digits_img, (SZ, SZ)) labels = np.repeat(np.arange(CLASS_N), len(digits)/CLASS_N) diff --git "a/\345\256\230\346\226\271samples/digits_adjust.py" "b/\345\256\230\346\226\271samples/digits_adjust.py" index 79c46d65..f1474fda 100755 --- "a/\345\256\230\346\226\271samples/digits_adjust.py" +++ "b/\345\256\230\346\226\271samples/digits_adjust.py" @@ -67,8 +67,7 @@ def get_dataset(self): def run_jobs(self, f, jobs): pool = ThreadPool(processes=cv2.getNumberOfCPUs()) - ires = pool.imap_unordered(f, jobs) - return ires + return pool.imap_unordered(f, jobs) def adjust_SVM(self): Cs = np.logspace(0, 10, 15, base=2) @@ -127,7 +126,7 @@ def f(k): args.setdefault('--model', 'svm') args.setdefault('--env', '') if args['--model'] not in ['svm', 'knearest']: - print('unknown model "%s"' % args['--model']) + print(f"""unknown model "{args['--model']}\"""") sys.exit(1) t = clock() diff --git "a/\345\256\230\346\226\271samples/digits_video.py" "b/\345\256\230\346\226\271samples/digits_video.py" index 2f79cb5c..3b4b71a4 100755 --- "a/\345\256\230\346\226\271samples/digits_video.py" +++ "b/\345\256\230\346\226\271samples/digits_video.py" @@ -25,15 +25,10 @@ def main(): classifier_fn = 'digits_svm.dat' if not os.path.exists(classifier_fn): - print('"%s" not found, run digits.py first' % classifier_fn) + print(f'"{classifier_fn}" not found, run digits.py first') return - if True: - model = cv2.ml.SVM_load(classifier_fn) - else: - model = cv2.ml.SVM_create() - model.load_(classifier_fn) #Known bug: https://github.com/opencv/opencv/issues/4969 - + model = cv2.ml.SVM_load(classifier_fn) while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) diff --git "a/\345\256\230\346\226\271samples/distrans.py" "b/\345\256\230\346\226\271samples/distrans.py" index 8abe460e..ed3b8145 100755 --- "a/\345\256\230\346\226\271samples/distrans.py" +++ "b/\345\256\230\346\226\271samples/distrans.py" @@ -42,10 +42,7 @@ def update(dummy=None): thrs = cv2.getTrackbarPos('threshold', 'distrans') mark = cv2.Canny(img, thrs, 3*thrs) dist, labels = cv2.distanceTransformWithLabels(~mark, cv2.DIST_L2, 5) - if voronoi: - vis = cm[np.uint8(labels)] - else: - vis = cm[np.uint8(dist*2)] + vis = cm[np.uint8(labels)] if voronoi else cm[np.uint8(dist*2)] vis[mark != 0] = 255 cv2.imshow('distrans', vis) diff --git "a/\345\256\230\346\226\271samples/fitline.py" "b/\345\256\230\346\226\271samples/fitline.py" index c91144c2..31b9fe0f 100755 --- "a/\345\256\230\346\226\271samples/fitline.py" +++ "b/\345\256\230\346\226\271samples/fitline.py" @@ -49,10 +49,7 @@ def sample_line(p1, p2, n, noise=0.0): dist_func_names = it.cycle('DIST_L2 DIST_L1 DIST_L12 DIST_FAIR DIST_WELSCH DIST_HUBER'.split()) -if PY3: - cur_func_name = next(dist_func_names) -else: - cur_func_name = dist_func_names.next() +cur_func_name = next(dist_func_names) if PY3 else dist_func_names.next() def update(_=None): noise = cv2.getTrackbarPos('noise', 'fit line') @@ -90,9 +87,6 @@ def update(_=None): update() ch = cv2.waitKey(0) if ch == ord('f'): - if PY3: - cur_func_name = next(dist_func_names) - else: - cur_func_name = dist_func_names.next() + cur_func_name = next(dist_func_names) if PY3 else dist_func_names.next() if ch == 27: break diff --git "a/\345\256\230\346\226\271samples/gaussian_mix.py" "b/\345\256\230\346\226\271samples/gaussian_mix.py" index 79c69fcd..2e1849d8 100755 --- "a/\345\256\230\346\226\271samples/gaussian_mix.py" +++ "b/\345\256\230\346\226\271samples/gaussian_mix.py" @@ -15,7 +15,7 @@ def make_gaussians(cluster_n, img_size): points = [] ref_distrs = [] - for i in xrange(cluster_n): + for _ in xrange(cluster_n): mean = (0.1 + 0.8*random.rand(2)) * img_size a = (random.rand(2, 2)-0.5)*img_size*0.1 cov = np.dot(a.T, a) + img_size*0.05*np.eye(2) diff --git "a/\345\256\230\346\226\271samples/hist.py" "b/\345\256\230\346\226\271samples/hist.py" index d1801c7e..627a4c74 100755 --- "a/\345\256\230\346\226\271samples/hist.py" +++ "b/\345\256\230\346\226\271samples/hist.py" @@ -35,8 +35,7 @@ def hist_curve(im): hist=np.int32(np.around(hist_item)) pts = np.int32(np.column_stack((bins,hist))) cv2.polylines(h,[pts],False,col) - y=np.flipud(h) - return y + return np.flipud(h) def hist_lines(im): h = np.zeros((300,256,3)) diff --git "a/\345\256\230\346\226\271samples/houghlines.py" "b/\345\256\230\346\226\271samples/houghlines.py" index 76e074cb..30012988 100755 --- "a/\345\256\230\346\226\271samples/houghlines.py" +++ "b/\345\256\230\346\226\271samples/houghlines.py" @@ -8,6 +8,7 @@ image argument defaults to ../data/pic1.png ''' + # Python 2/3 compatibility from __future__ import print_function @@ -28,27 +29,10 @@ dst = cv2.Canny(src, 50, 200) cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR) - if True: # HoughLinesP - lines = cv2.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10) - a,b,c = lines.shape - for i in range(a): - cv2.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA) - - else: # HoughLines - lines = cv2.HoughLines(dst, 1, math.pi/180.0, 50, np.array([]), 0, 0) - if lines is not None: - a,b,c = lines.shape - for i in range(a): - rho = lines[i][0][0] - theta = lines[i][0][1] - a = math.cos(theta) - b = math.sin(theta) - x0, y0 = a*rho, b*rho - pt1 = ( int(x0+1000*(-b)), int(y0+1000*(a)) ) - pt2 = ( int(x0-1000*(-b)), int(y0-1000*(a)) ) - cv2.line(cdst, pt1, pt2, (0, 0, 255), 3, cv2.LINE_AA) - - cv2.imshow("detected lines", cdst) + lines = cv2.HoughLinesP(dst, 1, math.pi/180.0, 40, np.array([]), 50, 10) + a,b,c = lines.shape + for i in range(a): + cv2.line(cdst, (lines[i][0][0], lines[i][0][1]), (lines[i][0][2], lines[i][0][3]), (0, 0, 255), 3, cv2.LINE_AA) cv2.imshow("source", src) cv2.waitKey(0) diff --git "a/\345\256\230\346\226\271samples/lappyr.py" "b/\345\256\230\346\226\271samples/lappyr.py" index c68e5e81..d673cb27 100755 --- "a/\345\256\230\346\226\271samples/lappyr.py" +++ "b/\345\256\230\346\226\271samples/lappyr.py" @@ -28,7 +28,7 @@ def build_lappyr(img, leveln=6, dtype=np.int16): img = dtype(img) levels = [] - for i in xrange(leveln-1): + for _ in xrange(leveln-1): next_img = cv2.pyrDown(img) img1 = cv2.pyrUp(next_img, dstsize=getsize(img)) levels.append(img-img1) diff --git "a/\345\256\230\346\226\271samples/letter_recog.py" "b/\345\256\230\346\226\271samples/letter_recog.py" index 7d0c4376..1bf1de83 100755 --- "a/\345\256\230\346\226\271samples/letter_recog.py" +++ "b/\345\256\230\346\226\271samples/letter_recog.py" @@ -161,7 +161,7 @@ def predict(self, samples): args.setdefault('--model', 'svm') args.setdefault('--data', '../data/letter-recognition.data') - print('loading data %s ...' % args['--data']) + print(f"loading data {args['--data']} ...") samples, responses = load_base(args['--data']) Model = models[args['--model']] model = Model() @@ -169,10 +169,10 @@ def predict(self, samples): train_n = int(len(samples)*model.train_ratio) if '--load' in args: fn = args['--load'] - print('loading model from %s ...' % fn) + print(f'loading model from {fn} ...') model.load(fn) else: - print('training %s ...' % Model.__name__) + print(f'training {Model.__name__} ...') model.train(samples[:train_n], responses[:train_n]) print('testing...') @@ -183,6 +183,6 @@ def predict(self, samples): if '--save' in args: fn = args['--save'] - print('saving model to %s ...' % fn) + print(f'saving model to {fn} ...') model.save(fn) cv2.destroyAllWindows() diff --git "a/\345\256\230\346\226\271samples/morphology.py" "b/\345\256\230\346\226\271samples/morphology.py" index 0b62784d..1ba83b7a 100755 --- "a/\345\256\230\346\226\271samples/morphology.py" +++ "b/\345\256\230\346\226\271samples/morphology.py" @@ -63,14 +63,14 @@ def update(dummy=None): op = opers[0] sz = sz*2+1 - str_name = 'MORPH_' + cur_str_mode.upper() - oper_name = 'MORPH_' + op.upper() + str_name = f'MORPH_{cur_str_mode.upper()}' + oper_name = f'MORPH_{op.upper()}' st = cv2.getStructuringElement(getattr(cv2, str_name), (sz, sz)) res = cv2.morphologyEx(img, getattr(cv2, oper_name), st, iterations=iters) - draw_str(res, (10, 20), 'mode: ' + cur_mode) - draw_str(res, (10, 40), 'operation: ' + oper_name) - draw_str(res, (10, 60), 'structure: ' + str_name) + draw_str(res, (10, 20), f'mode: {cur_mode}') + draw_str(res, (10, 40), f'operation: {oper_name}') + draw_str(res, (10, 60), f'structure: {str_name}') draw_str(res, (10, 80), 'ksize: %d iters: %d' % (sz, iters)) cv2.imshow('morphology', res) diff --git "a/\345\256\230\346\226\271samples/mosse.py" "b/\345\256\230\346\226\271samples/mosse.py" index 816c8e42..a2b8306a 100755 --- "a/\345\256\230\346\226\271samples/mosse.py" +++ "b/\345\256\230\346\226\271samples/mosse.py" @@ -73,7 +73,7 @@ def __init__(self, frame, rect): self.G = cv2.dft(g, flags=cv2.DFT_COMPLEX_OUTPUT) self.H1 = np.zeros_like(self.G) self.H2 = np.zeros_like(self.G) - for i in xrange(128): + for _ in xrange(128): a = self.preprocess(rnd_warp(img)) A = cv2.dft(a, flags=cv2.DFT_COMPLEX_OUTPUT) self.H1 += cv2.mulSpectrums(self.G, A, 0, conjB=True) @@ -110,8 +110,7 @@ def state_vis(self): kernel = np.uint8( (f-f.min()) / f.ptp()*255 ) resp = self.last_resp resp = np.uint8(np.clip(resp/resp.max(), 0, 1)*255) - vis = np.hstack([self.last_img, kernel, resp]) - return vis + return np.hstack([self.last_img, kernel, resp]) def draw_state(self, vis): (x, y), (w, h) = self.pos, self.size diff --git "a/\345\256\230\346\226\271samples/mouse_and_match.py" "b/\345\256\230\346\226\271samples/mouse_and_match.py" index f75b64ca..d3800cc4 100755 --- "a/\345\256\230\346\226\271samples/mouse_and_match.py" +++ "b/\345\256\230\346\226\271samples/mouse_and_match.py" @@ -68,7 +68,7 @@ def onmouse(event, x, y, flags, param): '''Loop through all the images in the directory''' for infile in glob.glob( os.path.join(path, '*.*') ): ext = os.path.splitext(infile)[1][1:] #get the filename extenstion - if ext == "png" or ext == "jpg" or ext == "bmp" or ext == "tiff" or ext == "pbm": + if ext in ["png", "jpg", "bmp", "tiff", "pbm"]: print(infile) img=cv2.imread(infile,1) diff --git "a/\345\256\230\346\226\271samples/opencv_version.py" "b/\345\256\230\346\226\271samples/opencv_version.py" index b26b55c1..efeb3405 100644 --- "a/\345\256\230\346\226\271samples/opencv_version.py" +++ "b/\345\256\230\346\226\271samples/opencv_version.py" @@ -10,6 +10,7 @@ --help: print this help ''' + # Python 2/3 compatibility from __future__ import print_function @@ -24,9 +25,9 @@ except IndexError: param = "" - if "--build" == param: + if param == "--build": print(cv2.getBuildInformation()) - elif "--help" == param: + elif param == "--help": print("\t--build\n\t\tprint complete build info") print("\t--help\n\t\tprint this help") else: diff --git "a/\345\256\230\346\226\271samples/opt_flow.py" "b/\345\256\230\346\226\271samples/opt_flow.py" index 3d4ef34d..ab1c8ace 100755 --- "a/\345\256\230\346\226\271samples/opt_flow.py" +++ "b/\345\256\230\346\226\271samples/opt_flow.py" @@ -43,8 +43,7 @@ def draw_hsv(flow): hsv[...,0] = ang*(180/np.pi/2) hsv[...,1] = 255 hsv[...,2] = np.minimum(v*4, 255) - bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) - return bgr + return cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) def warp_flow(img, flow): @@ -52,8 +51,7 @@ def warp_flow(img, flow): flow = -flow flow[:,:,0] += np.arange(w) flow[:,:,1] += np.arange(h)[:,np.newaxis] - res = cv2.remap(img, flow, None, cv2.INTER_LINEAR) - return res + return cv2.remap(img, flow, None, cv2.INTER_LINEAR) if __name__ == '__main__': import sys diff --git "a/\345\256\230\346\226\271samples/stereo_match.py" "b/\345\256\230\346\226\271samples/stereo_match.py" index 1f673301..9840caf9 100755 --- "a/\345\256\230\346\226\271samples/stereo_match.py" +++ "b/\345\256\230\346\226\271samples/stereo_match.py" @@ -70,7 +70,7 @@ def write_ply(fn, verts, colors): out_colors = colors[mask] out_fn = 'out.ply' write_ply('out.ply', out_points, out_colors) - print('%s saved' % 'out.ply') + print('out.ply saved') cv2.imshow('left', imgL) cv2.imshow('disparity', (disp-min_disp)/num_disp) diff --git "a/\345\256\230\346\226\271samples/tst_scene_render.py" "b/\345\256\230\346\226\271samples/tst_scene_render.py" index ce956f59..a6b2fd7c 100644 --- "a/\345\256\230\346\226\271samples/tst_scene_render.py" +++ "b/\345\256\230\346\226\271samples/tst_scene_render.py" @@ -55,12 +55,12 @@ def getRectInTime(self, time): if self.foreground is not None: tmp = np.array(self.center) + np.array((self.getXOffset(time), self.getYOffset(time))) x0, y0 = tmp - x1, y1 = tmp + self.foreground.shape[0:2] - return np.array([y0, x0, y1, x1]) + x1, y1 = tmp + self.foreground.shape[:2] else: x0, y0 = self.initialRect[0] + np.array((self.getXOffset(time), self.getYOffset(time))) x1, y1 = self.initialRect[2] + np.array((self.getXOffset(time), self.getYOffset(time))) - return np.array([y0, x0, y1, x1]) + + return np.array([y0, x0, y1, x1]) def getCurrentRect(self): diff --git "a/\345\256\230\346\226\271samples/turing.py" "b/\345\256\230\346\226\271samples/turing.py" index 5733d056..d5bc2604 100755 --- "a/\345\256\230\346\226\271samples/turing.py" +++ "b/\345\256\230\346\226\271samples/turing.py" @@ -45,7 +45,7 @@ def process_scale(a_lods, lod): d = a_lods[lod] - cv2.pyrUp(a_lods[lod+1]) - for i in xrange(lod): + for _ in xrange(lod): d = cv2.pyrUp(d) v = cv2.GaussianBlur(d*d, (3, 3), 0) return np.sign(d), v diff --git "a/\345\256\230\346\226\271samples/tutorial_code/core/mat_mask_operations/mat_mask_operations.py" "b/\345\256\230\346\226\271samples/tutorial_code/core/mat_mask_operations/mat_mask_operations.py" index 82208fa7..68acdcb8 100644 --- "a/\345\256\230\346\226\271samples/tutorial_code/core/mat_mask_operations/mat_mask_operations.py" +++ "b/\345\256\230\346\226\271samples/tutorial_code/core/mat_mask_operations/mat_mask_operations.py" @@ -15,11 +15,8 @@ def sharpen(my_image): sum = 5 * my_image[j, i, k] - my_image[j + 1, i, k] - my_image[j - 1, i, k]\ - my_image[j, i + 1, k] - my_image[j, i - 1, k]; - if sum > 255: - sum = 255 - if sum < 0: - sum = 0 - + sum = min(sum, 255) + sum = max(sum, 0) result[j, i, k] = sum ## [basic_method_loop] diff --git "a/\345\256\230\346\226\271samples/tutorial_code/imgProc/match_template/match_template.py" "b/\345\256\230\346\226\271samples/tutorial_code/imgProc/match_template/match_template.py" index 5c649a04..770e166e 100644 --- "a/\345\256\230\346\226\271samples/tutorial_code/imgProc/match_template/match_template.py" +++ "b/\345\256\230\346\226\271samples/tutorial_code/imgProc/match_template/match_template.py" @@ -78,10 +78,10 @@ def MatchingMethod(param): ## [best_match] ## [match_loc] - if (match_method == cv2.TM_SQDIFF or match_method == cv2.TM_SQDIFF_NORMED): - matchLoc = minLoc + if match_method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]: + matchLoc = minLoc else: - matchLoc = maxLoc + matchLoc = maxLoc ## [match_loc] ## [imshow] @@ -89,8 +89,6 @@ def MatchingMethod(param): cv2.rectangle(result, matchLoc, (matchLoc[0] + templ.shape[0], matchLoc[1] + templ.shape[1]), (0,0,0), 2, 8, 0 ) cv2.imshow(image_window, img_display) cv2.imshow(result_window, result) - ## [imshow] - pass if __name__ == "__main__": main(sys.argv[1:]) diff --git "a/\345\256\230\346\226\271samples/tutorial_code/ml/py_svm_opencv/hogsvm.py" "b/\345\256\230\346\226\271samples/tutorial_code/ml/py_svm_opencv/hogsvm.py" index 00586c85..c74fdfb2 100644 --- "a/\345\256\230\346\226\271samples/tutorial_code/ml/py_svm_opencv/hogsvm.py" +++ "b/\345\256\230\346\226\271samples/tutorial_code/ml/py_svm_opencv/hogsvm.py" @@ -27,8 +27,7 @@ def hog(img): bin_cells = bins[:10,:10], bins[10:,:10], bins[:10,10:], bins[10:,10:] mag_cells = mag[:10,:10], mag[10:,:10], mag[:10,10:], mag[10:,10:] hists = [np.bincount(b.ravel(), m.ravel(), bin_n) for b, m in zip(bin_cells, mag_cells)] - hist = np.hstack(hists) # hist is a 64 bit vector - return hist + return np.hstack(hists) ## [hog] img = cv2.imread('digits.png',0) diff --git "a/\345\256\230\346\226\271samples/video.py" "b/\345\256\230\346\226\271samples/video.py" index be15641b..bdfa6785 100755 --- "a/\345\256\230\346\226\271samples/video.py" +++ "b/\345\256\230\346\226\271samples/video.py" @@ -66,11 +66,7 @@ def render(self, dst): def read(self, dst=None): w, h = self.frame_size - if self.bg is None: - buf = np.zeros((h, w, 3), np.uint8) - else: - buf = self.bg.copy() - + buf = np.zeros((h, w, 3), np.uint8) if self.bg is None else self.bg.copy() self.render(buf) if self.noise > 0.0: @@ -172,7 +168,7 @@ def create_capture(source = 0, fallback = presets['chess']): chunks = source.split(':') # handle drive letter ('c:', ...) if len(chunks) > 1 and len(chunks[0]) == 1 and chunks[0].isalpha(): - chunks[1] = chunks[0] + ':' + chunks[1] + chunks[1] = f'{chunks[0]}:{chunks[1]}' del chunks[0] source = chunks[0] diff --git "a/\345\256\230\346\226\271samples/video_v4l2.py" "b/\345\256\230\346\226\271samples/video_v4l2.py" index 0af68e5d..ba03021d 100644 --- "a/\345\256\230\346\226\271samples/video_v4l2.py" +++ "b/\345\256\230\346\226\271samples/video_v4l2.py" @@ -54,8 +54,8 @@ def decode_fourcc(v): print("unsupported format") break - cv2.putText(img, "Mode: {}".format(fourcc), (15, 40), font, 1.0, color) - cv2.putText(img, "FPS: {}".format(fps), (15, 80), font, 1.0, color) + cv2.putText(img, f"Mode: {fourcc}", (15, 40), font, 1.0, color) + cv2.putText(img, f"FPS: {fps}", (15, 80), font, 1.0, color) cv2.imshow("Video", img) k = cv2.waitKey(1) diff --git "a/\345\256\230\346\226\271samples/watershed.py" "b/\345\256\230\346\226\271samples/watershed.py" index 30be82cf..37eb7fc5 100755 --- "a/\345\256\230\346\226\271samples/watershed.py" +++ "b/\345\256\230\346\226\271samples/watershed.py" @@ -33,7 +33,7 @@ class App: def __init__(self, fn): self.img = cv2.imread(fn) if self.img is None: - raise Exception('Failed to load image file: %s' % fn) + raise Exception(f'Failed to load image file: {fn}') h, w = self.img.shape[:2] self.markers = np.zeros((h, w), np.int32)