python - 如何使用Python在给定斜率和截距坐标(x,y)的图像上画一条线
问题描述
我有一条线的斜率,并且我有我希望这条线通过的截距的 x 和 y 坐标。本质上,我希望线条显示在图像本身上。
以下基本上是我迄今为止唯一的代码(只是变量):
slope = 3
intercepts = [7, 10]
我想使用 Python 来完成这项任务。任何帮助将不胜感激!
解决方案
import matplotlib.pyplot as plt
import random
x_intercept = 7
y_intercept = 10
my_slope = 3
def find_second_point(slope,x0,y0):
# this function returns two points which belongs to the line that has the slope
# inserted by the user and that intercepts the point (x0,y0) inserted by the user
q = y0 - (slope*x0) # calculate q
new_x1 = x0 + random.randint(x0,x0+10)
new_y1 = (slope*new_x1) + q
new_x2 = x0 - random.randint(x0,x0+10)
new_y2 = (slope*new_x2) + q
return new_x1, new_y1, new_x2, new_y2
new_x1, new_y1,new_x2, new_y2 = find_second_point(my_slope , x_intercept, y_intercept )
def slope(x1, y1, x2, y2):
return (y2-y1)/(x2-x1)
print(slope(x_intercept,y_intercept, new_x1, new_y1))
plt.figure(1) # create new figure
plt.plot((new_x2, new_x1),(new_y2, new_y1), c='r', label='Segment')
plt.scatter(x_intercept, y_intercept, c='b', linewidths=3, label='Intercept')
plt.scatter(new_x1, new_y1, c='g', linewidths=3, label='New Point 1')
plt.scatter(new_x2, new_y2, c='cyan', linewidths=3, label='New Point 2')
plt.legend() # add legend to image
plt.show()
输出:
slope
3.0
推荐阅读
- swift - 如何防止标题栏在 Metal 中引起渲染问题?
- ruby-on-rails-6 - Rails 6 和选择
- sas - 滚动标准偏差很难
- javascript - 请求的资源 API 网关上不存在“Access-Control-Allow-Origin”标头
- python - Python/Numpy:按公共元素对数组行进行分组
- python - 当我运行这个程序时,它会打印 Klkb,这是为什么呢?我已经把它分解了,似乎变量密文可能有问题
- javascript - npm 错误!404 未找到 - 获取 https://registry.npmjs.org/create-myreactnativeapp - 未找到
- prolog - maplist([X]>>(test(X,Xs)) 可以在范围外看到变量吗?
- android - 在 Kotlin 的 AsyncTask 中启动新活动
- python - 在 Python 3 中,我们可以在命名时不使用下划线来访问类属性的说明符吗?