How to auto-indent python code using keyboard shortcuts - python

I have following code:
for im_fn in tqdm(im_fns):
try:
_, fn = os.path.split(im_fn)
bfn, ext = os.path.splitext(fn)
if ext.lower() not in ['.jpg', '.png']:
continue
gt_path = os.path.join(DATA_FOLDER, "label", 'gt_' + bfn + '.txt')
img_path = os.path.join(DATA_FOLDER, "image", im_fn)
img = cv.imread(img_path)
img_size = img.shape
im_size_min = np.min(img_size[0:2])
im_size_max = np.max(img_size[0:2])
im_scale = float(600) / float(im_size_min)
if np.round(im_scale * im_size_max) > 1200:
im_scale = float(1200) / float(im_size_max)
new_h = int(img_size[0] * im_scale)
new_w = int(img_size[1] * im_scale)
new_h = new_h if new_h // 16 == 0 else (new_h // 16 + 1) * 16
new_w = new_w if new_w // 16 == 0 else (new_w // 16 + 1) * 16
re_im = cv.resize(img, (new_w, new_h), interpolation=cv.INTER_LINEAR)
re_size = re_im.shape
polys = []
with open(gt_path, 'r') as f:
lines = f.readlines()
for line in lines:
splitted_line = line.strip().lower().split(',')
x1, y1, x2, y2, x3, y3, x4, y4 = map(float, splitted_line[:8])
poly = np.array([x1, y1, x2, y2, x3, y3, x4, y4]).reshape([4, 2])
poly[:, 0] = poly[:, 0] / img_size[1] * re_size[1]
poly[:, 1] = poly[:, 1] / img_size[0] * re_size[0]
poly = orderConvex(poly)
polys.append(poly)
# cv.polylines(re_im, [poly.astype(np.int32).reshape((-1, 1, 2))], True,color=(0, 255, 0), thickness=2)
res_polys = []
for poly in polys:
# delete polys with width less than 10 pixel
if np.linalg.norm(poly[0] - poly[1]) < 10 or np.linalg.norm(poly[3] - poly[0]) < 10:
continue
res = shrink_poly(poly)
# for p in res:
# cv.polylines(re_im, [p.astype(np.int32).reshape((-1, 1, 2))], True, color=(0, 255, 0), thickness=1)
res = res.reshape([-1, 4, 2])
for r in res:
x_min = np.min(r[:, 0])
y_min = np.min(r[:, 1])
x_max = np.max(r[:, 0])
y_max = np.max(r[:, 1])
res_polys.append([x_min, y_min, x_max, y_max])
cv.imwrite(os.path.join(OUTPUT, "image", fn), re_im)
with open(os.path.join(OUTPUT, "label", bfn) + ".txt", "w") as f:
for p in res_polys:
line = ",".join(str(p[i]) for i in range(4))
f.writelines(line + "\r\n")
for p in res_polys:
cv.rectangle(re_im,(p[0],p[1]),(p[2],p[3]),color=(0,0,255),thickness=1)
cv.imshow("demo",re_im)
cv.waitKey(0)
except:
print("Error processing {}".format(im_fn))
In the above code I want to remove the uppermost for loop, try and except statement.
for im_fn in tqdm(im_fns):
try:
except:
print("Error processing {}".format(im_fn))
How ever after removing this I don't want to manually go in the remaining code and press backspace and manually put the indentations. IS there any key board shortcut which will auto indent the existing code after removing the for loop.

Select all the code you need to indent. With tab you will indent "in" and with Shift+tab you will indent it "out"

shift + tab works in the above scenario

Related

AttributeError: module 'tensorflow.core.framework.types_pb2' has no attribute 'SerializedDType'

`import cv2
import numpy as np
import time
from tensorflow.keras.models import load_model
sign_model = load_model('best_model.h5')
def detect_lines(image):
tuning min_threshold, minLineLength, maxLineGap is a trial and error process by hand
rho = 1 # precision in pixel, i.e. 1 pixel
angle = np.pi / 180 # degree in radian, i.e. 1 degree
min_threshold = 10 # minimal of votes
lines = cv2.HoughLinesP(image, rho, angle, min_threshold, np.array([]), minLineLength=8,
maxLineGap=4)
return lines
def mean_lines(frame, lines):
a = np.zeros_like(frame)
try:
left_line_x = []
left_line_y = []
right_line_x = []
right_line_y = []
for line in lines:
for x1, y1, x2, y2 in line:
slope = (y2 - y1) / (x2 - x1) # <-- Calculating the slope.
if abs(slope) < 0.5: # <-- Only consider extreme slope
continue
if slope <= 0: # <-- If the slope is negative, left group.
left_line_x.extend([x1, x2])
left_line_y.extend([y1, y2])
else: # <-- Otherwise, right group.
right_line_x.extend([x1, x2])
right_line_y.extend([y1, y2])
min_y = int(frame.shape[0] * (3 / 5)) # <-- Just below the horizon
max_y = int(frame.shape[0]) # <-- The bottom of the image
poly_left = np.poly1d(np.polyfit(
left_line_y,
left_line_x,
deg=1
))
left_x_start = int(poly_left(max_y))
left_x_end = int(poly_left(min_y))
poly_right = np.poly1d(np.polyfit(
right_line_y,
right_line_x,
deg=1
))
right_x_start = int(poly_right(max_y))
right_x_end = int(poly_right(min_y))
cv2.line(a, (left_x_start, max_y), (left_x_end, min_y), [255,255,0], 5)
cv2.line(a, (right_x_start, max_y), (right_x_end, min_y), [255,255,0], 5)
current_pix = (left_x_end+right_x_end)/2
except:
current_pix = 128
return a, current_pix
def region_of_interest(image):
(height, width) = image.shape
mask = np.zeros_like(image)
polygon = np.array([[
(0, height),
(0, 180),
(80, 130),
(256-80,130),
(width, 180),
(width, height),
np.int32)
cv2.fillPoly(mask, polygon, 255)
masked_image = image * (mask)
masked_image[:170,:]=0
return masked_image
def horiz_lines(mask):
roi = mask[160:180, 96:160]
try:
lines = detect_lines(roi)
lines = lines.reshape(-1,2,2)
slope = (lines[:,1,1]-lines[:,0,1]) / (lines[:,1,0]-lines[:,0,0])
if (lines[np.where(abs(slope)<0.2)]).shape[0] != 0:
detected = True
else:
detected = False
except:
detected = False
return detected
def turn_where(mask):
roi = mask[100:190, :]
cv2.imshow('turn where', roi)
lines = detect_lines(roi)
lines = lines.reshape(-1,2,2)
slope = (lines[:,1,1]-lines[:,0,1]) / (lines[:,1,0]-lines[:,0,0])
mean_pix = np.mean(lines[np.where(abs(slope)<0.2)][:,:,0])
return mean_pix
def detect_side(side_mask):
side_pix = np.mean(np.where(side_mask[150:190, :]>0), axis=1)[1]
return side_pix
def detect_sign(frame, hsv_frame):
types = ['left', 'straight', 'right']
mask = cv2.inRange(hsv_frame, np.array([100,160,90]), np.array([160,220,220]))
mask[:30,:]=0
try:
points, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
sorted_points = sorted(points, key=len)
if cv2.contourArea(sorted_points[-1])>30:
x,y,w,h = cv2.boundingRect(sorted_points[-1])
if (x>5) and (x+w<251) and (y>5) and (y+h<251):
sign = frame[y:y+h,x:x+w]
sign = cv2.resize(sign, (25,25))/255
frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,255),2)
return types[np.argmax(sign_model.predict(sign.reshape(1,25,25,3)))]
else:
return 'nothing'
else:
return 'nothing'
except:
return 'nothing'
def red_sign_state(red_mask):
points, _ = cv2.findContours(red_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
sorted_points = sorted(points, key=len)
try:
red_area = cv2.contourArea(sorted_points[-1])
if red_area > 50:
print('red sign detected!')
return True
else:
return False
except:
return False
def stop_the_car(car):
car.setSteering(0)
while car.getSpeed():
car.setSpeed(-100)
car.getData()
car.setSpeed(0)
return True
def turn_the_car(car,s,t):
time1 = time.time()
while((time.time()-time1)<t):
car.getData()
car.setSteering(s)
car.setSpeed(15)
def go_back(car, t):
time1 = time.time()
while((time.time()-time1)<t):
car.getData()
car.setSpeed(-15)
car.setSpeed(0)
`

Wrong ans given when using Python sympy with inequality

I make trying to check if a line segment (xy1) intersects with another (xy2).
Here's part of the code:
import numpy as np
from sympy import Symbol, Piecewise, lambdify, And
x1, y1 = Symbol('x1'), Symbol('y1')
x2, y2 = Symbol('x2'), Symbol('y2')
xx_u1 = 0.5
yy_u1 = 0.053
xx_u2 = 0.51
yy_u2 = 0.052
x_act1 = -2
y_act1 = 0.025
x_act2 = 0.5
y_act2 = 0.025
Ax = x1; Ay = y1; Bx = xx_u1; By = yy_u1; Cx = xx_u2; Cy = yy_u2
tmp1 = Piecewise( (1, (Cy - Ay)*(Bx - Ax) > (By - Ay)*(Cx - Ax)), (0, True))
tmp_1 = lambdify([x1,y1], tmp1, "numpy")
tmp_1_act = tmp_1(x_act1,y_act1)
Ax = x2; Ay = y2; Bx = xx_u1; By = yy_u1; Cx = xx_u2; Cy = yy_u2
tmp2 = Piecewise( (1, (Cy - Ay)*(Bx - Ax) > (By - Ay)*(Cx - Ax)), (0, True))
tmp_2 = lambdify([x2, y2], tmp2, "numpy")
tmp_2_act = tmp_2(x_act2, y_act2)
intersection_tmp1 = Piecewise( (1, tmp1 != tmp2), (0, True))
intersections1 = lambdify([x1, y1, x2, y2], intersection_tmp1, "numpy")
intersection_act1 = intersections1(x_act1, y_act1, x_act2, y_act2)
In this case, they shouldn't intersect. So intersection_act1 = 1.
However, I got 0. I only can get 1 if I use:
intersection_tmp1 = Piecewise( (1, tmp_1_act != tmp_2_act), (0, True))
instead of
intersection_tmp1 = Piecewise( (1, tmp1 != tmp2), (0, True))
Why is this so?

Marching Square algorithm in Python

The following Python source code is the implementation of Marching Square algorithm:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import cv2
from PIL import Image, ImageDraw
class Square():
A = [0, 0]
B = [0, 0]
C = [0, 0]
D = [0, 0]
A_data = 0.0
B_data = 0.0
C_data = 0.0
D_data = 0.0
def GetCaseId(self, threshold):
caseId = 0
if (self.A_data >= threshold):
caseId |= 1
if (self.B_data >= threshold):
caseId |= 2
if (self.C_data >= threshold):
caseId |= 4
if (self.D_data >= threshold):
caseId |= 8
return caseId
def GetLines(self, Threshold):
lines = []
caseId = self.GetCaseId(Threshold)
if caseId in (0, 15):
return []
if caseId in (1, 14, 10):
pX = (self.A[0] + self.B[0]) / 2
pY = self.B[1]
qX = self.D[0]
qY = (self.A[1] + self.D[1]) / 2
line = (pX, pY, qX, qY)
lines.append(line)
if caseId in (2, 13, 5):
pX = (self.A[0] + self.B[0]) / 2
pY = self.A[1]
qX = self.C[0]
qY = (self.A[1] + self.D[1]) / 2
line = (pX, pY, qX, qY)
lines.append(line)
if caseId in (3, 12):
pX = self.A[0]
pY = (self.A[1] + self.D[1]) / 2
qX = self.C[0]
qY = (self.B[1] + self.C[1]) / 2
line = (pX, pY, qX, qY)
lines.append(line)
if caseId in (4, 11, 10):
pX = (self.C[0] + self.D[0]) / 2
pY = self.D[1]
qX = self.B[0]
qY = (self.B[1] + self.C[1]) / 2
line = (pX, pY, qX, qY)
lines.append(line)
elif caseId in (6, 9):
pX = (self.A[0] + self.B[0]) / 2
pY = self.A[1]
qX = (self.C[0] + self.D[0]) / 2
qY = self.C[1]
line = (pX, pY, qX, qY)
lines.append(line)
elif caseId in (7, 8, 5):
pX = (self.C[0] + self.D[0]) / 2
pY = self.C[1]
qX = self.A[0]
qY = (self.A[1] + self.D[1]) / 2
line = (pX, pY, qX, qY)
lines.append(line)
return lines
def marching_square(xVector, yVector, Data, threshold):
linesList = []
Height = len(Data) # rows
Width = len(Data[1]) # cols
if ((Width == len(xVector)) and (Height == len(yVector))):
squares = np.full((Height - 1, Width - 1), Square())
sqHeight = squares.shape[0] # rows count
sqWidth = squares.shape[1] # cols count
for j in range(sqHeight): # rows
for i in range(sqWidth): # cols
a = Data[j + 1, i]
b = Data[j + 1, i + 1]
c = Data[j, i + 1]
d = Data[j, i]
A = [xVector[i], yVector[j + 1]]
B = [xVector[i + 1], yVector[j + 1]]
C = [xVector[i + 1], yVector[j]]
D = [xVector[i], yVector[j]]
squares[j, i].A_data = a
squares[j, i].B_data = b
squares[j, i].C_data = c
squares[j, i].D_data = d
squares[j, i].A = A
squares[j, i].B = B
squares[j, i].C = C
squares[j, i].D = D
list = squares[j, i].GetLines(threshold)
linesList = linesList + list
else:
raise AssertionError
return [linesList]
def main():
x = [i for i in range(256)]
y = [i for i in range(256)]
example_l = [[0 for i in range(256)] for j in range(256)]
for i in range(len(example_l)):
for j in range(len(example_l[0])):
example_l[i][j] = math.sin(i / 10.0)*math.cos(j / 10.0)
example = np.array(example_l)
im = Image.new('RGB', (256, 256), (128, 128, 128))
collection = marching_square(x, y, example, 0.9)
draw = ImageDraw.Draw(im)
for ln in collection:
for toup in ln:
draw.line(toup, fill=(255, 255, 0), width=1)
plt.axis("off")
plt.imshow( im )
plt.show()
if __name__ == '__main__':
main()
Output:
My question is: Why does this source code generate circular patterns?
what is the mathematical explanation of this circular pattern?
You are applying the marching squares algorithm to a sample of the surface defined by:
F(x,y) = sin(x)*cos(y)
If you plot it, e.g. with google here
You get a surface that looks like eggs boxes, and your marching squares algorithm is finding the isolines ("lines following a single data level, or isovalue.") at 0.9, which are circles. You can imagine this as the intersection of that surface with a plane parallel to the XY plane and at Z = 0.9.

polygon identification using python

i am having code that make an identification of points and build from them polygon shape
def load_annoataion(p):
'''
load annotation from the text file
:param p:
:return:
'''
text_polys = []
text_tags = []
if not os.path.exists(p):
return np.array(text_polys, dtype=np.float32)
with open(p, 'r') as f:
reader = csv.reader(f)
for line in reader:
label = line[-1]
# strip BOM. \ufeff for python3, \xef\xbb\bf for python2
line = [i.strip('\ufeff').strip('\xef\xbb\xbf') for i in line]
x1, y1, x2, y2, x3, y3, x4, y4 = list(map(float, line[:8]))
text_polys.append([[x1, y1], [x2, y2], [x3, y3], [x4, y4]])
if label == '*' or label == '###':
text_tags.append(True)
else:
text_tags.append(False)
return np.array(text_polys, dtype=np.float32), np.array(text_tags, dtype=np.bool)
def polygon_area(poly):
'''
compute area of a polygon
:param poly:
:return:
'''
edge = [
(poly[1][0] - poly[0][0]) * (poly[1][1] + poly[0][1]),
(poly[2][0] - poly[1][0]) * (poly[2][1] + poly[1][1]),
(poly[3][0] - poly[2][0]) * (poly[3][1] + poly[2][1]),
(poly[0][0] - poly[3][0]) * (poly[0][1] + poly[3][1])
]
return np.sum(edge)/2.
def check_and_validate_polys(polys, tags, xxx_todo_changeme):
'''
check so that the text poly is in the same direction,
and also filter some invalid polygons
:param polys:
:param tags:
:return:
'''
(h, w) = xxx_todo_changeme
if polys.shape[0] == 0:
return polys
polys[:, :, 0] = np.clip(polys[:, :, 0], 0, w-1)
polys[:, :, 1] = np.clip(polys[:, :, 1], 0, h-1)
validated_polys = []
validated_tags = []
for poly, tag in zip(polys, tags):
p_area = polygon_area(poly)
if abs(p_area) < 1:
# print poly
print('invalid poly')
continue
if p_area > 0:
print('poly in wrong direction')
poly = poly[(0, 3, 2, 1), :]
validated_polys.append(poly)
validated_tags.append(tag)
return np.array(validated_polys), np.array(validated_tags)
i am having a problem with this code with polygons are oriented along Y axis as
X1,Y1,X2,Y2,X3,Y3,X4,Y4
34,64,43,64,43,79,34,79
34,132,43,132,43,148,34,148
34,200,43,200,43,216,34,216
34,268,43,268,43,285,34,285
34,337,43,337,43,353,34,353
34,405,43,405,43,421,34,421
this picture may provide a better understanding
how i can modify the validation equation to accept polygon are oriented along Y axis

Creating a movie in Jython/Python

I am trying to make a movie, whilst creating frames through a loop. It is saving, but only the first frame (which it plays as a movie - short movie!) I've tried various things and cannot figure out what I am doing wrong. Thanks
def synthesiseFrame(folder):
folder =r"D:\FOLDER"
m=0.5
for x in range(1,121):
pic=makeEmptyPicture(960,540)
for x in range (0,960):
for y in range (0,540):
r=#some code
g=#some code
b=#some code
color =makeColor (r,g,b)
px= getPixel (pic, x, y)
setColor(px, color)
numStr=str(x)
m=m+0.0125
if x<10:
writePictureTo(pic, folder+"\pic00"+numStr+".png")
if x >=10 and x<100:
writePictureTo(pic, folder+"\pic0"+numStr+".png")
if x>=100:
writePictureTo(pic,folder+"\pic"+numStr+".png")
return movie
movie=synthesiseFrame(folder)
folder =r"D:\FOLDER"
file=r"D:\FOLDER\pic00.png"
movie=makeMovieFromInitialFile(file)
writeQuicktime(movie,"D:\FOLDER\movie.mov", 30)
playMovie(movie)
My first sight at JES video functions and at your code tells me something like (fully working example):
import os
import random
def synthesizeFrameAndCreateMovie(folder):
# Create an empty movie to receive the frames
movie = makeMovie()
# Compute & save the frames
w = 40
h = 25
nb_frames = 60 # Will give 60 frames at 30 fps => movie duration : 2 sec.
for z in range(0, nb_frames):
pic=makeEmptyPicture(w, h)
for x in range (0, w):
for y in range (0, h):
#makeColor() takes red, green, and blue (in that order) between 0 and 255
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
color = makeColor(r,g,b)
px = getPixel(pic, x, y)
setColor(px, color)
# Create one frame and inject in the movie object
filename = os.path.join(folder, 'pic%03d.png' % z)
writePictureTo(pic, filename)
addFrameToMovie(filename, movie)
# return the movie
return movie
movie = synthesizeFrameAndCreateMovie("D:\\FOLDER")
print movie
#writeQuicktime(movie,"D:\\FOLDER\\movie.mov", 30)
playMovie(movie)
Output (frames):
.............................................
EDIT :
More fun : animating a line (code taken form here)...
import os
import random
# Draw point, with check if the point is in the image area
def drawPoint(pic, col, x, y):
if (x >= 0) and (x < getWidth(pic)) and (y >= 0) and (y < getHeight(pic)):
px = getPixel(pic, x, y)
setColor(px, col)
# Draw line segment, given two points
# From Bresenham's line algorithm
# http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
def drawLine(pic, col, x0, y0, x1, y1):
dx = abs(x1-x0)
dy = abs(y1-y0)
sx = sy = 0
#sx = 1 if x0 < x1 else -1
#sy = 1 if y0 < y1 else -1
if (x0 < x1):
sx = 1
else:
sx = -1
if (y0 < y1):
sy = 1
else:
sy = -1
err = dx - dy
while (True):
drawPoint(pic, col, x0, y0)
if (x0 == x1) and (y0 == y1):
break
e2 = 2 * err
if (e2 > -dy):
err = err - dy
x0 = x0 + sx
if (x0 == x1) and (y0 == y1):
drawPoint(pic, col, x0, y0)
break
if (e2 < dx):
err = err + dx
y0 = y0 + sy
# Draw infinite line from segment
def drawInfiniteLine(pic, col, x0, y0, x1, y1):
# y = m * x + b
m = (y0-y1) / (x0-x1)
if (abs(m) > 100.0):
m = 100.0
# y0 = m * x0 + b => b = y0 - m * x0
b = y0 - m * x0
x0 = 0
y0 = int(m*x0 + b)
# get a 2nd point far away from the 1st one
x1 = getWidth(pic)
y1 = int(m*x1 + b)
drawLine(pic, col, x0, y0, x1, y1)
# Draw infinite line from origin point and angle
# Angle 'theta' expressed in degres
def drawInfiniteLineA(pic, col, x, y, theta):
# y = m * x + b
dx = y * tan(theta * pi / 180.0) # (need radians)
dy = y
if (dx == 0):
dx += 0.000000001 # Avoid to divide by zero
m = dy / dx
# y = m * x + b => b = y - m * x
b = y - m * x
# get a 2nd point far away from the 1st one
x1 = 2 * getWidth(pic)
y1 = m*x1 + b
drawInfiniteLine(pic, col, x, y, x1, y1)
def synthesizeFrameAndCreateMovie(folder):
# Create an empty movie to receive the frames
movie = makeMovie()
# Compute & save the frames
w = 40
h = 25
nb_frames = 120 # Will give 120 frames at 30 fps => movie duration : 4 sec.
for z in range(0, nb_frames):
pic = makeEmptyPicture(w, h)
addRectFilled(pic, 0, 0, w-1, h-1)
#makeColor() takes red, green, and blue (in that order) between 0 and 255
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
col = makeColor(r,g,b)
theta = z * 360 / nb_frames
if (theta != 180.0) and (theta != 0.0):
drawInfiniteLineA(pic, col, w//2, h//2, theta)
# Create one frame and inject in the movie object
filename = os.path.join(folder, 'pic%03d.png' % z)
writePictureTo(pic, filename)
addFrameToMovie(filename, movie)
# return the movie
return movie
movie = synthesizeFrameAndCreateMovie("/home/FOLDER")
print movie
#writeQuicktime(movie,"/home/golgauth/Desktop/FOLDER/movie.mov", 30)
#writeAVI(movie,"/home/golgauth/Desktop/FOLDER/movie.avi")
playMovie(movie)
Output (frames):
.............................................
I changed your code.
Used '%03d'%x instead of if*3.
change 'pic00.png' to 'pic001.png' because the loop in synthesiseFrame start from 1.
'\' -> os.path.join(..); Put import os if you didn't.
def synthesiseFrame(folder):
m = 0.5
for frameNumber in range(1,121):
pic=makeEmptyPicture(960,540)
for x in range (0,960):
for y in range (0,540):
r = #some code
g = #some code
b = #some code
color =makeColor (r,g,b)
px= getPixel (pic, x, y)
setColor(px, color)
m += 0.0125
writePictureTo(pic, os.path.join(folder, 'pic%03d.png' % frameNumber)) # 3 if -> no if
return movie
movie = synthesiseFrame(folder)
folder = r"D:\FOLDER"
file = r"D:\FOLDER\pic001.png" # 00 -> 001
movie=makeMovieFromInitialFile(file)
writeQuicktime(movie,"D:\FOLDER\movie.mov", 30)
playMovie(movie)
EDIT
x (in outer loop) -> frameNumber

Categories

Resources