Advertisement
TheDoskz

Graphic

Oct 17th, 2021 (edited)
690
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4.  
  5. def parser(filename, mode='v'):
  6.     with open(filename, 'r') as f:
  7.         f = f.read()
  8.     lst = []
  9.     for line in f.split('\n'):
  10.         if 'v' in line and mode == 'v':
  11.             lst.append(line.split()[1:-1])
  12.         if 'f' in line and mode == 'f':
  13.             lst.append(line.split()[1:])
  14.     if mode == 'f':
  15.         return np.array(lst, dtype=int) - 1
  16.     else:
  17.         return np.array(lst, dtype=float)
  18.  
  19.  
  20. def size_convert(vertexes, size, scale):
  21.     vertexes = (vertexes + scale) * size / (2 * scale)
  22.     return np.rint(vertexes).astype(int)
  23.  
  24.  
  25. def line(image, base_color, x0, y0, x1, y1):
  26.     size=len(image)
  27.     steep = False
  28.     if abs(x0 - x1) < abs(y0 - y1):
  29.         x0, y0 = y0, x0
  30.         x1, y1 = y1, x1
  31.         steep = True
  32.     dx = abs(x1 - x0)
  33.     dy = abs(y1 - y0)
  34.     signy = np.sign(y1 - y0)
  35.     error = 0
  36.     y = y0
  37.     for x in range(x0, x1):
  38.         color = base_color * (1 - np.sqrt((size/2 - x) ** 2 + (size/2 - y) ** 2) / size)
  39.         if steep:
  40.             image[y - 1, x - 1] = color
  41.         else:
  42.             image[x - 1, y - 1] = color
  43.         error += dy
  44.         if 2 * error >= dx:
  45.             y += signy
  46.             error -= dx
  47.  
  48.  
  49. def draw(vertexes, faces, image=np.zeros((1024, 1024, 3), dtype=np.uint8),
  50.          color=np.array([255, 255, 255], dtype=np.uint8)):
  51.     for first, second, third in faces:
  52.         line(image, color, vertexes[first, 0], vertexes[first, 1], vertexes[second, 0],
  53.              vertexes[second, 1])
  54.         line(image, color, vertexes[second, 0], vertexes[second, 1], vertexes[third, 0],
  55.              vertexes[third, 1])
  56.         line(image, color, vertexes[first, 0], vertexes[first, 1], vertexes[third, 0],
  57.              vertexes[third, 1])
  58.  
  59.     image = np.rot90(image)
  60.     plt.imsave("teapot.jpg", image)
  61.     plt.imshow(image)
  62.     plt.show()
  63.  
  64.  
  65. screen_size = 1024
  66. img = np.zeros((screen_size, screen_size, 3), dtype=np.uint8)+255
  67. color = np.array([255, 0, 0], dtype=np.uint8)
  68. scale = 3.5
  69. # print(img)
  70. #            Не трогать!
  71. model_vertexes = size_convert(parser('teapot.obj', mode='v'), screen_size, scale)
  72. faces = parser('teapot.obj', mode='f')
  73.  
  74. draw(model_vertexes, faces, img, color)
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement