I'm trying to re-adapt an adaptation of this code but I'm getting the error stated above.
I tried reading the docs, but I honestly didn't understand it.
The input is a vector that contains many polygons and I want to make them more rectangular.
def slope(x1, y1, x2, y2):
return (y2 - y1) / ((x2 - x1) + 0.00001) #I was getting DivisionByZero error
def intercept(y, slope, x):
return y - slope * x
def perpindicular(slope):
return -1 / slope
pth = r"C:\Users\whatever\...myVector.gpkg"
lyr = QgsVectorLayer(pth, "idk what i should put here", "ogr")
epsg = lyr.crs().postgisSrid()
uri = "Polygon?crs=epsg:{}&field=id:integer&index=yes".format(epsg)
rectangle = QgsVectorLayer(uri, 'Rectangles', 'memory')
p = rectangle.dataProvider()
for f in lyr.getFeatures():
g = f.geometry()
xmin, ymin, xmax, ymax = g.boundingBox().toRectF().getCoords()
pts = f.geometry().asPolygon()[0]
for i in range(len(pts)-1):
if pts[i][1] == ymax and pts[i+1][1] < pts[i][1]:
idx = i
if pts[i][1] == ymax and pts[i-1][1] < pts[i][1]:
idx = i-1
r = []
x1 = pts[idx][0]
y1 = pts[idx][1]
r.append(QgsPointXY(x1,y1))
x2 = pts[idx+1][0]
y2 = pts[idx+1][1]
r.append(QgsPointXY(x2,y2))
s1 = slope(x1, y1, x2, y2)
i1 = intercept(y1, s1, x1)
x3 = pts[idx+2][0]
y3 = pts[idx+2][1]
i2 = intercept(y3, s1, x3)
s3 = perpindicular(s1)
i3 = intercept(y2, s3, x2)
x4 = (i3 - i2)/(s1 - s3)
y4 = s3 * x4 + i3
r.append(QgsPointXY(x4, y4))
s4 = perpindicular(s1)
i4 = intercept(y1, s4, x1)
x5 = (i4 - i2)/(s1 - s4)
y5 = s4 * x5 + i4
r.extend([QgsPointXY(x5, y5),QgsPointXY(x1, y1)])
poly = []
poly.append(r)
g = QgsGeometry.fromPolygonXY(poly)
ft = QgsFeature()
ft.setAttributes([i])
ft.setGeometry(g)
p.addFeatures([ft])
QgsProject.instance().addMapLayer([rectangle, lyr])