cv2.fillConvexPoly not drawing entirely polygon - python
My code reads csv from annotations made in VIA (VGG IMAGE ANOTATOR) and draw its regions.
This is the code that draws the regions.
df = csv_file[csv_file['region_shape_attributes'] != '{}']
images = []
NAMES = []
p,r,point = 0,0,0
for index, img in enumerate(tqdm(img_list)):
if int(csv_file.region_count[index]) == 0:
continue
lista = csv_file[csv_file.img == img] #Recebe os dados encontrados dentro do csv para a imagem em questão
tamanho = lista.shape
if tamanho[0] > 1:
imagem = cv2.imread(os.path.join(img_dir, img)) #Carrega a imagem em questão
img_last = img
# Importa a mascara do indice de vegetacao:
msk = np.zeros(imagem.shape[:2], dtype = 'uint8') #Carrega as informações do tamanho da imagem
msk_name = os.path.join(img_dir, img.replace('.JPG', '_msk.png')) #Faz a junção do diretório com o nome da imagem, alterando seu formato
#print(msk_name) #Apresenta o nome da máscara com o diretório a ser salvo
for i in range(tamanho[0]):
line = lista.iloc[i,:] #Recebe todas as marcações realizadas dentro daquela imagem
region_shape = line.region_shape_attributes #Informa a posição onde o ponto se encontra
region_attributes = (line.region_attributes) #Informa a classe do ponto
region_attributes = re.findall('"([^"]*)"', region_attributes)
if 'polygon' in region_shape:
p+=1
line = region_shape.split("all_points")
x_coords = [float(s) for s in re.findall(r'-?\d+\.?\d*', line[1])]
y_coords = [float(s) for s in re.findall(r'-?\d+\.?\d*', line[2])]
coords = []
for x, y in zip(x_coords, y_coords):
coords.append([x,y])
pts = np.array(coords, dtype=np.int32)
cv2.fillConvexPoly(msk, pts, 1)
elif 'rect' in region_shape:
continue
r+=1
coords = [float(s) for s in re.findall(r'-?\d+\.?\d*', region_shape)] #Encontrando valores de x e y
cx = int(coords[0]) #Coordenadas no eixo X
cy = int(coords[1]) #Coordenadas no eixo y
width = int(coords[2])
height = int(coords[3])
cv2.rectangle(msk, (cx-width,cy-height), (cx+width, cy+height), 1, -1)
elif "\"point\"" in region_shape:
continue
point+=1
coords = [float(s) for s in re.findall(r'-?\d+\.?\d*', region_shape)] #Encontrando valores de x e y
cx = int(coords[0]) #Coordenadas no eixo X
cy = int(coords[1]) #Coordenadas no eixo y
width = 10
height = 10
cv2.rectangle(msk, (cx-width,cy-height), (cx+width, cy+height), 1, -1)
#cv2.imwrite(msk_name, msk.astype('uint8')) #Realiza o salvamento do background
im_l = [imagem, msk]
NAMES.append(img)
images.append(im_l)
break
print(p,r,point)
The problem is happening when why try to pass this image:
Original image
Instead of getting something like this:
Image in VIA
I get this:
Output
The points are:
array([[2148, 687],
[2120, 658],
[2100, 650],
[2062, 631],
[2028, 596],
[1994, 580],
[1978, 580],
[1938, 557],
[1914, 519],
[1877, 491],
[1845, 485],
[1825, 468],
[1785, 466],
[1747, 470],
[1716, 481],
[1687, 494],
[1648, 535],
[1626, 573],
[1598, 604],
[1597, 640],
[1597, 687],
[1574, 727],
[1578, 782],
[1582, 816],
[1593, 849],
[1597, 866],
[1605, 895],
[1598, 947],
[1589, 978],
[1566, 1043],
[1546, 1067],
[1518, 1080],
[1506, 1104],
[1482, 1148],
[1481, 1227],
[1484, 1251],
[1498, 1271],
[1498, 1289],
[1514, 1310],
[1544, 1331],
[1554, 1350],
[1546, 1433],
[1536, 1481],
[1521, 1504],
[1518, 1548],
[1510, 1579],
[1508, 1606],
[1512, 1647],
[1493, 1698],
[1493, 1739],
[1504, 1752],
[1525, 1784],
[1548, 1836],
[1557, 1853],
[1574, 1872],
[1567, 1889],
[1581, 1917],
[1563, 1946],
[1566, 1971],
[1577, 1978],
[1577, 1998],
[1585, 2014],
[1602, 2032],
[1621, 2112],
[1631, 2147],
[1642, 2184],
[1647, 2213],
[1663, 2271],
[1688, 2305],
[1720, 2339],
[1763, 2366],
[1821, 2394],
[1846, 2399],
[1888, 2376],
[1930, 2185],
[1946, 2136],
[1951, 2117],
[1974, 1993],
[1805, 1662],
[2010, 1562],
[1910, 1425],
[1993, 1387],
[1933, 1255],
[1951, 970],
[2035, 1215],
[2163, 1273],
[2230, 1109],
[2468, 1104],
[2581, 1306],
[2675, 1226],
[2609, 1118],
[2588, 1040],
[2561, 1000],
[2528, 976],
[2484, 976],
[2456, 984],
[2384, 960],
[2347, 834],
[2306, 824],
[2269, 794],
[2242, 789],
[2198, 744],
[2176, 736],
[2173, 731]], dtype=int32)
I already checked if the points I read are correct, and they are.
If I call cv2.polylines(msk, [pts], True, 1) instead of cv2.fillConvexPoly(msk, pts, 1, 10) I get the desired output, but unfilled:
with polylines
So I'd like to know if you guys can help me finding out why fillConvexPoly isn't filling properly. I didn't find anything about limit of points I can pass throug the function and even when I slice my array to decrease it the output is the same (cv2.fillConvexPoly(msk, pts[int(pts.shape[0]/2):], 1)):
The same problem using half the array
You could use cv2.drawContours() functions to achieve that. If you have your points:
points = [[2148, 687],
[2120, 658],
[2100, 650],
[2062, 631],
[2028, 596],
[1994, 580],
[1978, 580],
[1938, 557],
[1914, 519],
[1877, 491],
[1845, 485],
[1825, 468],
[1785, 466],
[1747, 470],
[1716, 481],
[1687, 494],
[1648, 535],
[1626, 573],
[1598, 604],
[1597, 640],
[1597, 687],
[1574, 727],
[1578, 782],
[1582, 816],
[1593, 849],
[1597, 866],
[1605, 895],
[1598, 947],
[1589, 978],
[1566, 1043],
[1546, 1067],
[1518, 1080],
[1506, 1104],
[1482, 1148],
[1481, 1227],
[1484, 1251],
[1498, 1271],
[1498, 1289],
[1514, 1310],
[1544, 1331],
[1554, 1350],
[1546, 1433],
[1536, 1481],
[1521, 1504],
[1518, 1548],
[1510, 1579],
[1508, 1606],
[1512, 1647],
[1493, 1698],
[1493, 1739],
[1504, 1752],
[1525, 1784],
[1548, 1836],
[1557, 1853],
[1574, 1872],
[1567, 1889],
[1581, 1917],
[1563, 1946],
[1566, 1971],
[1577, 1978],
[1577, 1998],
[1585, 2014],
[1602, 2032],
[1621, 2112],
[1631, 2147],
[1642, 2184],
[1647, 2213],
[1663, 2271],
[1688, 2305],
[1720, 2339],
[1763, 2366],
[1821, 2394],
[1846, 2399],
[1888, 2376],
[1930, 2185],
[1946, 2136],
[1951, 2117],
[1974, 1993],
[1805, 1662],
[2010, 1562],
[1910, 1425],
[1993, 1387],
[1933, 1255],
[1951, 970],
[2035, 1215],
[2163, 1273],
[2230, 1109],
[2468, 1104],
[2581, 1306],
[2675, 1226],
[2609, 1118],
[2588, 1040],
[2561, 1000],
[2528, 976],
[2484, 976],
[2456, 984],
[2384, 960],
[2347, 834],
[2306, 824],
[2269, 794],
[2242, 789],
[2198, 744],
[2176, 736],
[2173, 731]]
Then you can do:
cv2.drawContours(image, np.array([points]), -1, (1), thickness=-1)
Note that thickness=-1 means to fill the contour. For more information on drawing contours go here
Outputs:
Related
how can i smooth the graph values or extract main signals only
when i try to run the code below i get this graph my code: from numpy import nan import json import os import numpy as np import subprocess import math import matplotlib.pyplot as plt from statistics import mean, stdev def smooth(t): new_t = [] for i, x in enumerate(t): neighbourhood = t[max(i-2,0): i+3] m = mean(neighbourhood) s = stdev(neighbourhood, xbar=m) if abs(x - m) > s: x = ( t[i - 1 + (i==0)*2] + t[i + 1 - (i+1==len(t))*2] ) / 2 new_t.append(x) return new_t def outLiersFN(*U): outliers=[] # after preprocessing list #preprocessing Fc =| 2*LF1 prev by 1 - LF2 prev by 2 | c0 = -2 #(previous) by 2 #from original c1 =-1 #(previous) #from original c2 =0 #(current) #from original c3 = 1 #(next) #from original preP = U[0] # original list if c2 == 0: outliers.append(preP[0]) c1+=1 c2+=1 c0+=1 c3+=1 oldlen = len(preP) M_RangeOfMotion = 90 while oldlen > c2 : if c3 == oldlen: outliers.insert(c2, preP[c2]) #preP[c2] >> last element in old list break if (preP[c2] > M_RangeOfMotion and preP[c2] < (preP[c1] + preP[c3])/2) or (preP[c2] < M_RangeOfMotion and preP[c2] > (preP[c1] + preP[c3])/2): #Check Paper 3.3.1 Equ = (preP[c1] + preP[c3])/2 #fn of preprocessing # From third index # ==== inserting current frame formatted_float = "{:.2f}".format(Equ) #with .2 number only equu = float(formatted_float) #from string float to float outliers.insert(c2,equu) # insert the preprocessed value to the List c1+=1 c2+=1 c0+=1 c3+=1 else : Equ = preP[c2] # fn of preprocessing #put same element (do nothing) formatted_float = "{:.2f}".format(Equ) # with .2 number only equu = float(formatted_float) # from string float to float outliers.insert(c2, equu) # insert the preprocessed value to the List c1 += 1 c2 += 1 c0 += 1 c3 += 1 return outliers def remove_nan(list): newlist = [x for x in list if math.isnan(x) == False] return newlist the_angel = [176.04, 173.82, 170.09, 165.3, 171.8, 178.3, 178.77, 179.24, 179.93, 180.0, 173.39, 166.78, 166.03, 165.28, 165.72, 166.17, 166.71, 167.26, 168.04, 167.22, 166.68, 166.13, 161.53, 165.81, 170.1, 170.05, 170.5, 173.01, 176.02, 174.53, 160.09, 146.33, 146.38, 146.71, 150.33, 153.95, 154.32, 154.69, 134.52, 114.34, 115.6, 116.86, 134.99, 153.12, 152.28, 151.43, 151.36, 152.32, 158.9, 166.52, 177.74, 178.61, 179.47, 167.44, 155.4, 161.54, 167.68, 163.96, 160.24, 137.45, 114.66, 117.78, 120.89, 139.95, 139.62, 125.51, 111.79, 112.07, 112.74, 110.22, 107.7, 107.3, 106.52, 105.73, 103.07, 101.35, 102.5, 104.59, 104.6, 104.49, 104.38, 102.81, 101.25, 100.62, 100.25, 100.15, 100.32, 99.84, 99.36, 100.04, 100.31, 99.14, 98.3, 97.92, 97.41, 96.9, 96.39, 95.88, 95.9, 95.9, 96.02, 96.14, 96.39, 95.2, 94.56, 94.02, 93.88, 93.8, 93.77, 93.88, 94.04, 93.77, 93.65, 93.53, 94.2, 94.88, 92.59, 90.29, 27.01, 32.9, 38.78, 50.19, 61.59, 61.95, 62.31, 97.46, 97.38, 97.04, 96.46, 96.02, 96.1, 96.33, 95.61, 89.47, 89.34, 89.22, 89.48, 89.75, 90.02, 90.28, 88.16, 88.22, 88.29, 88.17, 88.17, 94.98, 94.84, 94.69, 94.94, 94.74, 94.54, 94.69, 94.71, 94.64, 94.58, 94.19, 94.52, 94.85, 87.7, 87.54, 87.38, 95.71, 96.57, 97.11, 97.05, 96.56, 96.07, 95.76, 95.56, 95.35, 95.28, 95.74, 96.2, 96.32, 96.33, 96.2, 96.14, 96.07, 96.07, 96.12, 96.17, 96.28, 96.31, 96.33, 96.16, 96.05, 95.94, 95.33, 88.96, 95.0, 95.78, 88.19, 88.19, 88.19, 87.92, 87.93, 88.03, 87.94, 87.86, 87.85, 87.89, 88.08, 88.01, 87.88, 88.02, 88.15, 88.15, 88.66, 88.73, 88.81, 88.41, 88.55, 88.68, 88.69, 88.02, 87.35, 95.19, 95.39, 95.38, 95.37, 95.27, 95.17, 95.33, 95.32, 95.31, 95.37, 95.42, 95.34, 95.44, 95.53, 95.47, 95.41, 95.13, 94.15, 94.78, 97.64, 97.1, 96.87, 97.03, 96.76, 35.44, 23.63, 23.27, 24.71, 26.16, 96.36, 113.13, 129.9, 96.82, 63.74, 34.25, 33.42, 32.6, 30.69, 31.06, 31.43, 97.14, 97.51, 97.23, 98.54, 100.13, 100.95, 28.82, 33.81, 66.81, 99.82, 102.63, 101.9, 101.44, 102.19, 103.22, 103.67, 104.13, 104.07, 104.73, 105.46, 103.74, 102.02, 103.32, 102.59, 29.54, 28.08, 28.76, 29.79, 30.82, 113.51, 129.34, 145.16, 143.18, 148.29, 153.67, 166.14, 161.16, 151.64, 149.27, 146.9, 151.67, 153.02, 149.28, 145.53, 149.1, 152.67, 158.78, 164.89, 164.84, 164.8, 162.11, 159.42, 156.73, 156.28, 155.83, 156.4, 161.0, 165.59, 164.44, 159.73, 155.76, 156.97, 158.92, 159.15, 159.39, 159.99, 160.44, 160.88, 163.89, 166.9, 167.71, 167.11, 167.0, 167.44, 168.38, 153.16, 137.94, 137.65, 152.09, 169.49, 171.36, 173.22, 174.01, 174.0, 174.2, 174.41, 157.74, 141.09, 149.32, 157.57, 156.4, 148.4, 140.78, 141.06, 141.73, 143.05, 143.91, 156.59, 169.29, 172.17, 175.05, 175.29, 175.27, 175.15, 175.02, 174.81, 174.59, 174.76, 174.94, 175.18, 175.41, 175.23, 174.51, 174.64, 174.77, 174.56, 173.25, 172.38, 174.17, 176.4, 177.27, 177.29, 177.33, 178.64, 179.98, 179.99, 176.0, 172.88, 173.77, 173.8, 173.97, 174.72, 175.24, 176.89, 179.07, 179.27, 178.78, 178.29, 175.61, 174.21, 172.8, 173.05, 173.41, 173.77, 174.65, 175.52, 175.58, 176.15, 176.71, 159.12, 141.54, 141.12, 155.62, 170.53, 165.54, 160.71, 158.22, 156.35, 156.82, 158.55, 160.27, 161.33, 162.39, 162.37, 159.48, 156.59, 156.77, 158.05, 159.32, 158.49, 157.66, 157.7, 157.74, 158.44, 159.14, 150.13, 143.06, 136.0, 125.7, 115.41, 111.19, 106.97, 107.1, 107.24, 107.45, 107.67, 113.34, 119.01, 144.87, 170.73, 174.31, 177.89, 174.78, 171.67, 163.26, 134.58, 105.9, 102.98, 100.77, 101.05, 101.39, 101.73, 99.79, 98.71, 97.64, 97.8, 97.89, 96.67, 95.45, 94.33, 93.38, 92.44, 48.53, 91.4, 91.35, 91.34, 91.33, 90.92, 90.51, 88.63, 87.0, 86.74, 86.48, 96.79, 96.09, 95.46, 95.39, 94.32, 93.25, 93.31, 93.37, 93.11, 92.57, 93.41, 94.25, 96.48, 92.71, 88.94, 90.07, 90.43, 78.06, 77.69, 77.32, 90.1, 89.15, 89.14, 88.85, 88.38, 87.63, 121.2, 120.66, 86.89, 86.42, 85.69, 84.86, 84.86, 85.34, 85.82, 86.07, 86.32, 85.82, 85.32, 86.23, 86.69, 87.15, 87.04, 86.87, 86.58, 86.0, 85.41, 85.41, 85.53, 85.66, 85.7, 85.72, 85.75, 85.92, 86.09, 85.77, 85.45, 84.94, 85.55, 86.16, 86.21, 86.1, 85.77, 85.27, 84.56, 84.99, 85.38, 85.42, 85.98, 86.54, 86.5, 86.45, 86.56, 86.63, 86.35, 86.08, 85.82, 85.51, 85.21, 84.6, 84.84, 84.97, 85.1, 86.12, 86.88, 86.8, 86.46, 86.47, 87.23, 87.8, 88.0, 88.08, 88.16, 87.72, 87.63, 87.37, 86.42, 86.48, 87.24, 87.97, 88.09, 88.19, 88.32, 88.44, 87.82, 87.2, 86.03, 85.78, 91.5, 93.0, 88.2, 88.52, 88.42, 87.28, 85.73, 85.62, 85.5, 85.5, 87.06, 87.6, 88.1, 88.31, 88.53, 88.77, 89.14, 89.52, 89.46, 89.4, 90.28, 89.74, 91.28, 92.17, 92.16, 92.15, 93.08, 94.0, 94.66, 95.32, 94.13, 93.7, 93.32, 93.69, 94.58, 95.47, 97.25, 99.03, 99.63, 99.67, 99.71, 100.33, 101.58, 103.36, 103.49, 103.41, 106.31, 109.34, 109.28, 109.21, 107.76, 106.31, 105.43, 104.94, 104.44, 111.19, 117.93, 115.59, 113.24, 116.15, 119.06, 125.43, 140.72, 156.0, 161.7, 143.52, 135.33, 127.13, 127.68, 148.68, 169.68, 172.2, 174.72, 174.75, 174.66, 158.57, 142.63, 145.13, 153.29, 161.45, 163.34, 165.24, 162.25, 159.89, 159.07, 156.39, 155.21, 156.04, 159.29, 160.07, 160.85, 163.45, 162.93, 161.71, 160.06, 158.4, 144.74, 132.64, 134.57, 150.22, 165.86, 172.95, 174.12, 175.3, 175.5, 176.31, 177.71, 179.72, 168.13, 156.55, 146.24, 155.75, 176.0, 175.99, 175.98, 176.0, 176.02, 176.25, 175.13, 174.26, 173.38, 173.37, 173.46, 176.34, 174.55, 172.77, 168.45, 166.35, 166.47, 168.81, 167.43, 166.79, 167.35, 168.65, 168.51, 168.37, 168.88, 169.74, 171.19, 171.33, 169.91, 168.49, 167.11, 166.83, 167.01, 168.68, 170.34, 170.43, 172.15, 173.86, 177.62, 177.61, 175.34, 173.06, 176.47, 179.87, 179.9, 177.67, 175.67, 175.39, 175.36, 177.03, 176.0, 174.98, 174.96, 174.94, 175.76, 176.57, 169.05, 162.99, 164.97, 168.74, 172.51, 167.38, 165.08, 163.03, 163.81, 164.83, 164.81, 164.8, 165.88, 165.36, 159.61, 153.86, 153.57, 153.61, 153.65, 154.62, 155.58, 157.97, 156.35, 155.66, 154.98, 156.11, 157.24, 159.25, 159.6, 160.43, 161.26, 164.71, 168.17, 147.46, 126.92, 106.38, 105.23, 104.4, 105.37, 106.65, 109.21, 107.44, 104.65, 101.86, 102.35, 102.84, 102.79, 102.19, 101.59, 100.98, 100.38, 98.72, 97.73, 97.32, 96.9, 95.11, 93.97, 94.12, 94.12, 93.1, 92.08, 89.29, 90.35, 90.35, 90.35, 90.35, 86.95, 86.37, 86.06, 85.74, 94.56, 93.16, 92.46, 91.76, 88.55, 85.33, 87.52, 92.18, 93.68, 95.18, 94.4, 92.17, 89.94, 89.4, 89.37, 99.44, 100.98, 102.52, 103.18, 88.96, 88.23, 87.5, 85.2, 85.19, 86.87, 121.42, 155.96, 155.97, 155.97, 86.2, 86.5, 86.8, 87.22, 87.36, 87.34, 87.03, 87.04, 87.05, 86.36, 85.68, 85.71, 85.84, 85.93, 86.01, 86.04, 86.08, 85.92, 86.05, 86.18, 86.17, 86.19, 86.23, 86.22, 86.09, 85.92, 85.66, 85.69, 85.69, 85.31, 84.91, 84.93, 84.95, 84.93, 84.91, 84.9, 84.9, 84.9, 84.9, 85.38, 85.52, 85.66, 85.66, 85.4, 85.14, 85.47, 85.8, 85.72, 85.64, 86.09, 85.84, 85.27, 85.47, 85.66, 85.59, 85.52, 85.38, 85.39, 85.28, 85.17, 85.39, 85.7, 85.98, 86.26, 86.61, 92.97, 93.15, 86.58, 86.58, 86.53, 86.47, 98.55, 99.41, 100.16, 100.9, 89.19, 90.28, 91.38, 91.39, 91.4, 91.44, 92.05, 131.05, 170.63, 170.13, 162.43, 125.64, 88.85, 88.85, 99.08, 100.38, 101.69, 100.74, 99.79, 96.33, 93.31, 93.73, 94.87, 96.01, 96.93, 97.85, 98.97, 97.85, 98.14, 99.37, 102.01, 103.8, 105.58, 108.52, 108.12, 107.72, 106.75, 106.82, 109.08, 112.37, 112.52, 112.66, 112.97, 114.12, 115.64, 117.1, 118.57, 126.13, 133.69, 149.27, 163.96, 166.62, 169.27, 164.94, 160.61, 149.35, 141.18, 143.41, 143.57, 149.26, 157.49, 159.94, 151.93, 147.47, 145.97, 145.56, 145.15, 143.85, 142.54, 142.18, 142.43, 143.12, 144.41, 144.38, 151.99, 159.59, 174.81, 174.94, 175.84, 176.87, 162.41, 152.94, 151.59, 155.24, 155.22, 155.19, 155.04] p0 = outLiersFN(smooth(remove_nan(the_angel))) the_angel = p0 plt.plot(the_angel) #list(filter(fun, L1)) plt.show() print((the_angel)) how can i smooth the values in (the_angel) to get graph like this (red line) i mean ignoring all unnecessary and noisy values and get only main line instead you can edit my code or suggest me new filter or algorithm
pandas has a rolling() method for dataframes that you can use to calculate the mean over a window of values, e.g. the 70 closest ones: import pandas as pd import matplotlib.pyplot as plt WINDOW_SIZE = 70 the_angel = [176.04, 173.82, 170.09, 165.3, 171.8, # ... ] df = pd.DataFrame({'the angel': the_angel}) df[f'mean of {WINDOW_SIZE}'] = df['the angel'].rolling( window=WINDOW_SIZE, center=True).mean() df.plot(color=['blue', 'red']);
Syntax highlight python
I want to make a simple python highlighter for a homework, but things like comments or strings are not being colored, I'm supposed to use regular expressions for the homework (regex). import re #Expresiones regulares de regEX palabrasRe= re.compile(r'\b(False|class|return|None|continue|lambda|try|True|def|nonlocal|while|for|and|del|not|with|as|elif|or|yield|assert|if|else|pass|break|except|raise|list|print|from|import|except|finally|raise|global|in|is|del|with|as|async|await)') string1 = re.compile(r'[\'][\W\w]*[\']') string2 = re.compile(r'[\"][\W\w]*[\"]') comentario1 = re.compile(r'#.+\n') comentario2 = re.compile(r'(\'{3}(.+\n)*\'{3})') num = re.compile(r'(\d+(?:\.\d+)?)') identificador = re.compile(r'\b[a-zA-z]\w*') operadores= re.compile(r'(\+|\-|\/|\*|\%|\>|\<|\=)') caractEspeciales = re.compile(r'\W') #Abrir el archivo para leer archivo = open('ej.py', "r") lineas = archivo.readlines() archivo.close() #Archivo de html html = open('holamundo.html','w') mensaje = " " #Listas para las coordenadas pos_ren=0 copalRev=[] costr1=[] costr2=[] cocomen1=[] cocomen2=[] conum=[] coiden=[] coop=[] corcarE=[] #Leer elementos del archivo para revisarlos for i in lineas: ren=lineas[pos_ren] menren=ren mensaje+="<p>" search = operadores.finditer(menren) for match in search: cor=match.span() coop.append(cor) #print(match) search = identificador.finditer(menren) for match in search: cor=match.span() coiden.append(cor) #print(match) search = num.finditer(menren) for match in search: cor=match.span() conum.append(cor) #print(match) search = palabrasRe.finditer(menren) for match in search: cor=match.span() copalRev.append(cor) #print(match) search = string2.finditer(menren) for match in search: cor=match.span() costr2.append(cor) search = string1.finditer(menren) for match in search: cor=match.span() costr1.append(cor) search = comentario1.finditer(menren) for match in search: cor=match.span() cocomen1.append(cor) search = comentario2.finditer(menren) for match in search: cor=match.span() cocomen2.append(cor) search = caractEspeciales.finditer(menren) for match in search: cor=match.span() corcarE.append(cor) for i in coop: x,y=i print(i) print(ren) pal=ren[x:y] mensaje2="<FONT COLOR='#FFA500'>"+pal+"</FONT>" # COLOR OPERADORES menren= menren.replace(pal, mensaje2) #ren[x:y]= mensaje2 coop=[] for i in coiden: x,y=i print(i) pal=ren[x:y] print(pal) mensaje4="<FONT COLOR='#5982D3'>"+pal+"</FONT>" # COLOR IDENTIFICADORES menren= menren.replace(pal, mensaje4) #ren[x:y]= mensaje3 coiden=[] for i in conum: x,y=i print(i) pal=ren[x:y] print(pal) mensaje5="<FONT COLOR='#8032E4'>"+pal+"</FONT>" # COLOR NUMEROS menren= menren.replace(pal, mensaje5) #ren[x:y]= mensaje3 conum=[] for i in copalRev: x,y=i print(i) pal=ren[x:y] print(pal) mensaje6="<FONT COLOR='#FFCE3O'>"+pal+"</FONT>" # COLOR PALABRAS RESERVADAS menren= menren.replace(pal, mensaje6) #ren[x:y]= mensaje3 copalRev=[] for i in cocomen1: x,y=i print(i) pal=ren[x:y] print(pal) mensaje7="<FONT COLOR='#FFFFFF'>"+pal+"</FONT>" # COLOR PALABRAS RESERVADAS menren= menren.replace(pal, mensaje7) #ren[x:y]= mensaje3 cocomen1=[] for i in costr1: x,y=i print(i) pal=ren[x:y] print(pal) mensaje8="<FONT COLOR='#FFFFFF'>"+pal+"</FONT>" # COLOR PALABRAS RESERVADAS menren= menren.replace(pal, mensaje8) #ren[x:y]= mensaje3 costr1=[] mensaje+=menren+"</p>" pos_ren+=1 html.write("<html><head></head><body bgcolor='#232231' >"+mensaje+"</body></html>") html.close() It should be coloring reserved words, both types of strings, both type of comments, numbers, identifiers, operators and special characters. So far I'm getting this:
I tried to refactor this to stop all of your manual copy/pasting with loops... but I'm too tired to debug why it's not running now. Here's how far I got. import re from collections import defaultdict # Expresiones regulares de regEX KEYWORDS = [ 'False', 'class', 'return', 'None', 'continue', 'lambda', 'try', 'True', 'def', 'nonlocal', 'while', 'for', 'and', 'del', 'not', 'with', 'as', 'elif', 'or', 'yield', 'assert', 'if', 'else', 'pass', 'break', 'except', 'raise', 'list', 'print', 'from', 'import', 'except', 'finally', 'raise', 'global', 'in', 'is', 'del', 'with', 'as', 'async', 'await', ] REGEXES = { 'palabrasRe': re.compile(fr'\b({"|".join(KEYWORDS)})'), 'string1': re.compile(r'[\'][\W\w]*[\']'), 'string2': re.compile(r'[\"][\W\w]*[\"]'), 'comentario1': re.compile(r'#.+\n'), 'comentario2': re.compile(r'(\'{3}(.+\n)*\'{3})'), 'num': re.compile(r'(\d+(?:\.\d+)?)'), 'identificador': re.compile(r'\b[a-zA-z]\w*'), 'operadores': re.compile(r'(\+|\-|\/|\*|\%|\>|\<|\=)'), 'caractEspeciales': re.compile(r'\W'), } COORDS_TRANSLATION = { 'palabrasRe': 'copalRev', 'string1': 'costr1', 'string2': 'costr2', 'comentario1': 'cocomen1', 'comentario2': 'cocomen2', 'num': 'conum', 'identificador': 'coiden', 'operadores': 'coop', 'caractEspeciales': 'corcarE', } COLORS = { 'copalRev': '#FFCE3O', 'costr1': '#FFFFFF', 'costr2': '#', 'cocomen1': '#FFFFFF', 'cocomen2': '#', 'conum': '#8032E4', 'coiden': '#5982D3', 'coop': '#FFA500', 'corcarE': '#', } # Abrir el archivo para leer with open('scratch_2.py', "r") as archivo: lineas = archivo.readlines() # Archivo de html html = open('holamundo.html', 'w') mensaje = " " # Listas para las coordenadas # Lists for the coordinates pos_ren = 0 coordinates = defaultdict(list) # Leer elementos del archivo para revisarlos for i in lineas: ren = lineas[pos_ren] menren = ren mensaje += "<p>" for name, regex in REGEXES.items(): search = REGEXES[name].finditer(menren) for match in search: cor = match.span() coordinates[COORDS_TRANSLATION[name]].append(cor) for name2, color in COLORS.items(): for j in coordinates[name2]: x, y = j print(j) print(ren) pal = ren[x:y] mensaje = f"<FONT COLOR='#{color}'>{pal}</FONT>" # COLOR OPERADORES menren = menren.replace(pal, mensaje) coordinates[name2].clear() mensaje += menren + "</p>" pos_ren += 1 html.write(f"<html><head></head><body bgcolor='#232231' >{mensaje}</body></html>") html.close()
How to visualize high-dimension vectors as points in 2D plane?
For example, there are three vectors as below. [ 0.0377, 0.1808, 0.0807, -0.0703, 0.2427, -0.1957, -0.0712, -0.2137, -0.0754, -0.1200, 0.1919, 0.0373, 0.0536, 0.0887, -0.1916, -0.1268, -0.1910, -0.1411, -0.1282, 0.0274, -0.0781, 0.0138, -0.0654, 0.0491, 0.0398, 0.1696, 0.0365, 0.2266, 0.1241, 0.0176, 0.0881, 0.2993, -0.1425, -0.2535, 0.1801, -0.1188, 0.1251, 0.1840, 0.1112, 0.3172, 0.0844, -0.1142, 0.0662, 0.0910, 0.0416, 0.2104, 0.0781, -0.0348, -0.1488, 0.0129], [-0.1302, 0.1581, -0.0897, 0.1024, -0.1133, 0.1076, 0.1595, -0.1047, 0.0760, 0.1092, 0.0062, -0.1567, -0.1448, -0.0548, -0.1275, -0.0689, -0.1293, 0.1024, 0.1615, 0.0869, 0.2906, -0.2056, 0.0442, -0.0595, -0.1448, 0.0167, -0.1259, -0.0989, 0.0651, -0.0424, 0.0795, -0.1546, 0.1330, -0.2284, 0.1672, 0.1847, 0.0841, 0.1771, -0.0101, -0.0681, 0.1497, 0.1226, 0.1146, -0.2090, 0.3275, 0.0981, -0.3295, 0.0590, 0.1130, -0.0650], [-0.1745, -0.1940, -0.1529, -0.0964, 0.2657, -0.0979, 0.1510, -0.1248, -0.1541, 0.1782, -0.1769, -0.2335, 0.2011, 0.1906, -0.1918, 0.1896, -0.2183, -0.1543, 0.1816, 0.1684, -0.1318, 0.2285, 0.1784, 0.2260, -0.2331, 0.0523, 0.1882, 0.1764, -0.1686, 0.2292] How to plot them as three points in the same 2D plane like this picture below? Thanks!
I use PCA from sklearn, maybe this code help you: import matplotlib.pyplot as plt import numpy as np from sklearn.decomposition import PCA usa = [ 0.0377, 0.1808, 0.0807, -0.0703, 0.2427, -0.1957, -0.0712, -0.2137, -0.0754, -0.1200, 0.1919, 0.0373, 0.0536, 0.0887, -0.1916, -0.1268, -0.1910, -0.1411, -0.1282, 0.0274, -0.0781, 0.0138, -0.0654, 0.0491, 0.0398, 0.1696, 0.0365, 0.2266, 0.1241, 0.0176, 0.0881, 0.2993, -0.1425, -0.2535, 0.1801, -0.1188, 0.1251, 0.1840, 0.1112, 0.3172, 0.0844, -0.1142, 0.0662, 0.0910, 0.0416, 0.2104, 0.0781, -0.0348, -0.1488, 0.0129] obama = [-0.1302, 0.1581, -0.0897, 0.1024, -0.1133, 0.1076, 0.1595, -0.1047, 0.0760, 0.1092, 0.0062, -0.1567, -0.1448, -0.0548, -0.1275, -0.0689, -0.1293, 0.1024, 0.1615, 0.0869, 0.2906, -0.2056, 0.0442, -0.0595, -0.1448, 0.0167, -0.1259, -0.0989, 0.0651, -0.0424, 0.0795, -0.1546, 0.1330, -0.2284, 0.1672, 0.1847, 0.0841, 0.1771, -0.0101, -0.0681, 0.1497, 0.1226, 0.1146, -0.2090, 0.3275, 0.0981, -0.3295, 0.0590, 0.1130, -0.0650] nationality = [-0.1745, -0.1940, -0.1529, -0.0964, 0.2657, -0.0979, 0.1510, -0.1248, -0.1541, 0.1782, -0.1769, -0.2335, 0.2011, 0.1906, -0.1918, 0.1896, -0.2183, -0.1543, 0.1816, 0.1684, -0.1318, 0.2285, 0.1784, 0.2260, -0.2331, 0.0523, 0.1882, 0.1764, -0.1686, 0.2292] pca = PCA(n_components=1) X = np.array(usa).reshape(2,len(usa)//2) X = pca.fit_transform(X) Y = np.array(obama).reshape(2,len(obama)//2) Y = pca.fit_transform(Y) Z = np.array(nationality).reshape(2,len(nationality)//2) Z = pca.fit_transform(Z) x_coordinates = [X[0][0], Y[0][0], Z[0][0]] y_coordinates = [X[1][0], Y[1][0], Z[1][0]] colors = ['r','g','b'] annotations=["U.S.A","Obama","Nationality"] plt.figure(figsize=(8,6)) plt.scatter(x_coordinates, y_coordinates, marker=",", color=colors,s=300) for i, label in enumerate(annotations): plt.annotate(label, (x_coordinates[i], y_coordinates[i])) plt.show() output:
How to use Python to parse a SVG document from URL (get points of a polyline)
I'm looking for a Python extension to parse a SVG's "points" values from the <polyline> elements and print them? Possibly to parse it from the URL? or I could save the SVG and do it locally. I just need it to parse the points values and print them separately for each polyline element. So it will print something like this for each points value of the current <polyline> element. [[239,274],[239,274],[239,274],[239,275],[239,275],[238,276],[238,276],[237,276],[237,276],[236,276],[236,276],[236,277] [236,277],[235,277],[235,277],[234,278],[234,278],[233,279],[233,279],[232,280] [232,280],[231,280],[231,280],[230,280],[230,280],[230,280],[229,280],[229,280]] So after the first polyline element gets parsed and printed, it would parse the next polyline element and get the value for points and print it just like the first one until there is no more to be printed. The SVG's URL: http://colorillo.com/bx0l.inline.svg Here is a HTML example of a polyline element from the SVG <polyline points="239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280" style="fill: none; stroke: #000000; stroke-width: 1; stroke-linejoin: round; stroke-linecap: round; stroke-antialiasing: false; stroke-antialias: 0; opacity: 0.8"/> I'm just looking for some quick help, and a example.. If you're able to help me out that would be neat.
I believe there is an HTML extraction package somewhere, but this is the kind of task I would do with core python, and the regular expressions module. Let txt be the text you presented <polyline..., so: Importing regular expression module In [22]: import re Performing the search: In [24]: g = re.search('polyline points="(.*?)"', txt) In the above regex I use polyline points=" as an anchor (I omitted the < because it has a meaning in regex`) and capture all the rest until the next quotation marks. The text you want is achieved by: In [25]: g.group(1) Out[25]: '239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280' Update It's safer to use xml to parse the data, here is one way to do it (xml.etree is included with the standard library): In [32]: import xml.etree.ElementTree as ET In [33]: root = ET.fromstring(txt) Since your data is formatted as a root tag already, you don't need futher extractions: In [35]: root.tag Out[35]: 'polyline' And all the properties are actually XML attributes, converted to a dictionary: In [37]: root.attrib Out[37]: {'points': '239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280', 'style': 'fill: none; stroke: #000000; stroke-width: 1; stroke-linejoin: round; stroke-linecap: round; stroke-antialiasing: false; stroke-antialias: 0; opacity: 0.8'} So here you have it: In [38]: root.attrib['points'] Out[38]: '239,274 239,274 239,274 239,275 239,275 238,276 238,276 237,276 237,276 236,276 236,276 236,277 236,277 235,277 235,277 234,278 234,278 233,279 233,279 232,280 232,280 231,280 231,280 230,280 230,280 230,280 229,280 229,280' If you like further to split this to groups according to commas and spaces, I would do this: Get all groups separated by a space using split with no arguments: >>> p = g.group(1).split() >>> p ['239,274', '239,274', '239,274', '239,275', '239,275', '238,276', '238,276', '237,276', '237,276', '236,276', '236,276', '236,277', '236,277', '235,277', '235,277', '234,278', '234,278', '233,279', '233,279', '232,280', '232,280', '231,280', '231,280', '230,280', '230,280', '230,280', '229,280', '229,280'] Now for each string, split it at the comma which will return a list of strings. I use map to convert each such list to a list of ints: >>> p2 = [list(map(int, numbers.split(','))) for numbers in p] >>> p2 [[239, 274], [239, 274], [239, 274], [239, 275], [239, 275], [238, 276], [238, 276], [237, 276], [237, 276], [236, 276], [236, 276], [236, 277], [236, 277], [235, 277], [235, 277], [234, 278], [234, 278], [233, 279], [233, 279], [232, 280], [232, 280], [231, 280], [231, 280], [230, 280], [230, 280], [230, 280], [229, 280], [229, 280]] And this will shed some more light: >>> '123,456'.split(',') ['123', '456'] >>> list(map(int, '123,456'.split(','))) [123, 456]
Below import xml.etree.ElementTree as ET from collections import namedtuple import requests import re Point = namedtuple('Point', 'x y') all_points = [] r = requests.get('http://colorillo.com/bx0l.inline.svg') if r.status_code == 200: data = re.sub(' xmlns="[^"]+"', '', r.content.decode('utf-8'), count=1) root = ET.fromstring(data) poly_lines = root.findall('.//polyline') for poly_line in poly_lines: tmp = [] _points = poly_line.attrib['points'].split(' ') for _p in _points: tmp.append(Point(*[int(z) for z in _p.split(',')])) all_points.append(tmp) for points in all_points: tmp = [str([p.x, p.y]).replace(' ','') for p in points] line = ','.join(tmp) print('[' + line + ']')
ClassB=[ClassA,ClassA,ClassA] cant print ClassB and index it. Python
I want to make a deck out of tarjeta, but i cant seem to print it and i cant use index. The Class Tarjeta works but when i append it to Mazo and print it, it gives me the same thing as if i didnt have the str thingy. paises_por_tarjeta is a {} class Tarjeta(object): #this is ClassA """Implementacion de una tarjeta de pais.""" def __init__(self, pais=None, tipo=0): """Constructor desde pais y tipo.""" self.pais = pais self.tipo = tipo def __str__(self): """Representacion grafica.""" return "(%s,%s)"%(self.pais, NOMBRE_TARJETAS[self.tipo]) class Mazo(object): #ClassB """Implementacion del mazo de tarjetas de pais.""" def __init__(self, paises_por_tarjeta): #paises_por_tarjeta is a {} that has the suit as key and countries as value """Creacion desde un diccionario de paises segun tipo. Debe inicializar el mazo con todas las tarjetas mezcladas.""" self.mazo=[] for i in range(0,4): for x in paises_por_tarjeta[i]: self.mazo.append(Tarjeta(x,i)) max_cartas=len(self.mazo) for k in range(max_cartas): #mezcla el mazo j=random.randrange(k,max_cartas) self.mazo[k],self.mazo[j]=self.mazo[j],self.mazo[k] def __str__(self): return str(self.mazo) EDIT: here are the NOMBRE_TARJETAS and paises_por_tarjeta: TARJETA_COMODIN = 0 TARJETA_GALEON = 1 TARJETA_GLOBO = 2 TARJETA_CANON = 3 NOMBRE_TARJETAS = { TARJETA_COMODIN: 'comodin', TARJETA_GALEON: 'galeon', TARJETA_GLOBO: 'globo', TARJETA_CANON: 'canon', } paises_por_tarjeta = { TARJETA_COMODIN: ['Argentina', 'Taimir'], TARJETA_GALEON: ['Alaska', 'Alemania', 'Borneo', 'Brasil', 'China', 'Gran Bretana', 'Groenlandia', 'Islandia', 'Israel', 'Madagascar', 'Mongolia', 'Nueva York', 'Peru', 'Siberia', 'Suecia', 'Turquia', 'Zaire'], TARJETA_GLOBO: ['Chile', 'Colombia', 'Egipto', 'Espana', 'Etiopia', 'Francia', 'Gobi', 'India', 'Iran', 'Italia', 'Kamchatka', 'Rusia', 'Sumatra', 'Uruguay', 'Yukon'], TARJETA_CANON: ['Arabia', 'Aral', 'Australia', 'California', 'Canada', 'Japon', 'Java', 'Labrador', 'Malasia', 'Mexico', 'Oregon', 'Polonia', 'Sahara', 'Sudafrica', 'Tartaria', 'Terranova'], } Any help would be appreciated, thanks!
You can try using this __str__ implementation for Mazo: def __str__(self): return str([str(k) for k in self.mazo]) Edit: If you want your class to support indexing, you can implement the method __getitem__: def __getitem__(self, index): return self.mazo[index]