我正在尝试在我的第一个python应用程序中遵循dry原则(我是一个经验丰富的.NET开发人员)。我已经能够将大部分重复的代码转移到可重用的函数中。
例如,以下是我如何为Matplotlib绘图创建线条(边界框):
def generate_bounding_box_polygon(comma_delimited_rect: str):
box_coordinates = comma_delimited_rect.strip().split(',')
x = int(box_coordinates[0].strip())
y = int(box_coordinates[1].strip())
width = int(box_coordinates[2].strip())
height = int(box_coordinates[3].strip())
bottom_left = [x, y]
bottom_right = [x + width, y]
top_left = [x, y + height]
top_right = [x + width, y + height]
points = [bottom_left, top_left, top_right, bottom_right, bottom_left]
polygon = plt.Polygon(points, fill=None, edgecolor='xkcd:rusty red', closed=False)
return polygon
我在为我的绘图创建边界框时重用了这个。此嵌套for循环位于多个函数中,因此
generate_bounding_boxes
功能好整洁
for region in result["regions"]:
region_box = generate_bounding_box_polygon(region["boundingBox"])
plt.gca().add_line(region_box)
for line in region["lines"]:
line_box = generate_bounding_box_polygon(line["boundingBox"])
plt.gca().add_line(line_box)
for word in line["words"]:
detected_text += word
word_box = generate_bounding_box_polygon(word["boundingBox"])
plt.gca().add_line(word_box)
# RELEVANT this is the code I want to move into a function
box_coordinates = word["boundingBox"].strip().split(',')
x = int(box_coordinates[0].strip())
y = int(box_coordinates[1].strip())
plt.gca().text(x, y-10, word["text"], fontsize=8)
但是,注意最后一个代码注释,我还想移动
text
方法转换为函数,但需要引用
plt.gca()
如何将其作为参数传递给函数?我尝试了以下方法(参见第二个参数,
plot
)就像我在C中做的那样,但它不起作用,而且可能在python中是不好的做法:
def render_text(comma_delimited_rect: str, plot: matplotlib.pyplot):
box_coordinates = comma_delimited_rect.strip().split(',')
x = int(box_coordinates[0].strip())
y = int(box_coordinates[1].strip())
plt.gca().text(x, y-10, word["text"], fontsize=8)
注:
plt
定义为
import matplotlib.pyplot as plt