Skip to content

Sourcery refactored master branch #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self, name, image, weight=1):

class opencv_windows_management:
def __init__(self):
self.windows = dict()
self.windows = {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function opencv_windows_management.__init__ refactored with the following changes:


root = tk.Tk()
screen_width = root.winfo_screenwidth()
Expand Down
8 changes: 2 additions & 6 deletions ch04-图片/show_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 39-46 refactored with the following changes:

This removes the following comments ( why? ):

#TODO 分辨率太大,需要缩放
# if t.any():
# if temp == img:
# t = temp == img
# if t.all():


import numpy as np
import cv2, sys

Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion ch05-视频/5.VideoPlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 27-27 refactored with the following changes:


FRAME_NOW = cap.get(cv2.CAP_PROP_POS_FRAMES)
print('当前帧数', FRAME_NOW) # 当前帧数 122.0
Expand Down
14 changes: 6 additions & 8 deletions ch05-视频/5.VideoWriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment on lines -21 to +29
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 21-31 refactored with the following changes:


key = cv2.waitKey(1)
if key == ord("q"):
Expand Down
2 changes: 1 addition & 1 deletion ch05-视频/VideoCaptureOnePicture.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 32-32 refactored with the following changes:


cap.release()
cv2.destroyAllWindows()
2 changes: 1 addition & 1 deletion ch06-绘图函数/画圆圈.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 35-35 refactored with the following changes:

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,))
Expand Down
2 changes: 1 addition & 1 deletion ch07-把鼠标当画笔/鼠标左右键回调函数.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function click_event refactored with the following changes:

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, strRGB, (x, y), font, 1, (255, 255, 255), 2)
cv2.imshow('original', img)
Expand Down
6 changes: 1 addition & 5 deletions ch08-用滑动条做调色板/8.createTrackbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 33-37 refactored with the following changes:

cv2.imshow('image', img)
k = cv2.waitKey(1) # & 0xFF
if k == ord("q"):
Expand Down
3 changes: 2 additions & 1 deletion ch10-图像上的算术运算/图像相减2.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
图像相减2.py:
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 48-48 refactored with the following changes:


import cv2
import numpy as np
import matplotlib.pyplot as plt
Expand Down Expand Up @@ -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)))
Expand Down
3 changes: 2 additions & 1 deletion ch10-图像上的算术运算/图像相减_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
图像相减_camera.py:
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 52-52 refactored with the following changes:


import cv2
import numpy as np

Expand Down Expand Up @@ -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():
Expand Down
5 changes: 3 additions & 2 deletions ch20-图像金字塔/20.Apple_orange.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
4. 在拉普拉斯的每一层 图像 合 苹果的左 与橘子的右 合 5. 根据 合后的图像 字塔 建原始图像。
'''


Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 23-30 refactored with the following changes:

import cv2
import numpy as np, sys

Expand All @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
aruco11.py:
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 31-32 refactored with the following changes:


import time, cv2
# import cv2.aruco as A
import numpy as np
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function make_grayscale refactored with the following changes:



def main():
Expand Down
6 changes: 2 additions & 4 deletions ch21-轮廓Contours/draw最大的轮廓.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
draw最大的轮廓.py:
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 25-28 refactored with the following changes:

This removes the following comments ( why? ):

#面积大小


import cv2
import numpy as np

Expand All @@ -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)#按面积大小,从大到小排序

Expand Down
3 changes: 1 addition & 2 deletions ch22-直方图/22.3-2D直方图.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

"""


Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 39-40 refactored with the following changes:

import cv2
import numpy as np

Expand All @@ -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
3 changes: 1 addition & 2 deletions ch22-直方图/hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function hist_curve refactored with the following changes:



def hist_lines(im):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 56-56 refactored with the following changes:

plt.show()
9 changes: 4 additions & 5 deletions ch26-Hough圆环变换/HoughCircles_camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines -53 to +62
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 53-63 refactored with the following changes:

This removes the following comments ( why? ):

# 静止画面,不用重复计算

#
# 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()
Expand Down
4 changes: 1 addition & 3 deletions ch26-Hough圆环变换/HoughCircles_chess.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Comment on lines -18 to +23
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function detect_weiqi refactored with the following changes:

return txt, threshold


Expand Down
10 changes: 1 addition & 9 deletions ch37-特征匹配/37.4-SIFT_match.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 28-36 refactored with the following changes:

This removes the following comments ( why? ):

# Apply ratio test
# 比值测试,首先获取与 A距离最近的点 B (最近)和 C (次近),
# 因为假设匹配是一一对应的,真正的匹配的理想距离为0
# 只有当 B/C 小于阀值时(0.75)才被认为是匹配,

# 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)
Expand Down
3 changes: 2 additions & 1 deletion ch37-特征匹配/37.5-FLANN匹配器.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 41-41 refactored with the following changes:




import numpy as np
import cv2
from matplotlib import pyplot as plt
Expand All @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
findHomography.py:联合使用特征提取和 calib3d 模块中的 findHomography 在复杂图像中查找已知对象
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 31-35 refactored with the following changes:

This removes the following comments ( why? ):

# store all the good matches as per Lowe's ratio test.


import numpy as np
import cv2
from matplotlib import pyplot as plt
Expand All @@ -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 的变换矩 就可以使用它将查 图像的四个 点 四个 变换到目标图像中去了。然后再绘制出来。
Expand Down
2 changes: 1 addition & 1 deletion ch43-姿势估计/calib3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 75-75 refactored with the following changes:

cv2.destroyAllWindows()

#如果你对计算机图形学感兴趣的 为了增加图像的真实性 你可以使用 OpenGL 来渲染更复杂的图形。 下一个目标
2 changes: 1 addition & 1 deletion ch44-对极几何/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 67-67 refactored with the following changes:

if m.distance < 0.8 * n.distance:
good.append(m)
pts2.append(kp2[m.trainIdx].pt)
Expand Down
3 changes: 1 addition & 2 deletions ch47-支持向量机/47.2-使用SVM进行-手写数据OCR.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function hog refactored with the following changes:

This removes the following comments ( why? ):

# hist is a 64 bit vector



# 最后 和前 一样 我们将大图分割成小图。使用每个数字的前 250 个作 为训练数据
Expand Down
3 changes: 2 additions & 1 deletion ch48-K值聚类/48.2.3_颜色量化2.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
48.2.3_颜色量化.py:
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 42-42 refactored with the following changes:


# 色 化就是减少图片中 色数目的一个 程。为什么 减少图片中的 色呢 减少内存消耗 有些 备的 源有 只能显示很少的 色。在 种情 况下就 色 化。我们使用 K 值聚类的方法来 色 化。
# 没有什么新的知 介绍了。现在有 3 个特征 R G B。所以我们 把图片数据变形成 Mx3 M 是图片中像素点的数目 的向 。聚类完成后 我们用聚类中心值替换与其同组的像素值 样结果图片就只含有指定数目的 色了。下 是代码
# -*- coding: utf-8 -*-
Expand Down Expand Up @@ -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)

#最大的色块

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@
2-fastNlMeansDenoisingMulti.py:
"""

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 17-17 refactored with the following changes:


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
Expand Down
Loading