map(lambda x: int(x * 255), list(cmap(1. * i / faller['dist']))[:-1]) for i in range(faller['dist']) ] def run(self): cells = self.np.zeros((self.width, self.height, 3), dtype=self.np.uint8) # render the fallers on remove = [] for f in self.fallers: f['y'] += f['speed'] for i in xrange(f['dist']): try: if int(f['y']) - i >= 0: cells[f['x'], int(f['y']) - i] = f['cols'][i] except IndexError, e: pass if f['y'] - f['dist'] > self.height: remove.append(f) self.fallers.append(self.make_faller()) map(self.fallers.remove, remove) return cells if __name__ == "__main__": from demo import show show(Runner, fps=24)
output2_opencl = cl.Buffer(self.ctx, mf.WRITE_ONLY, output2.nbytes) output_opencl = cl.Buffer(self.ctx, mf.WRITE_ONLY, output.nbytes) self.prg.mandelbrot(self.queue, output.shape, None, q_opencl, self.lut_opencl, output_opencl, output2_opencl, maxiter).wait() cl.enqueue_copy(self.queue, output2, output2_opencl) # return self.lut[output2] cl.enqueue_copy(self.queue, output, output_opencl).wait() return output, output2 def run(self): start = self.time.time() self.cells = self.mandelbrot_set3(self.xmin, self.xmax, self.ymin, self.ymax, width=self.width, height=self.height) # print "calculating", self.time.time() - start, self.cells.shape self.update_pos() return self.cells, "{:.2f} - {:.2f}\n{:.2f} - {:.2f}".format( self.xmin, self.xmax, self.ymin, self.ymax) if __name__ == "__main__": from demo import show show(Runner, fps=90, rows=900, cols=900, scale=1)
import numpy as np from demo import read, show from skimage import transform img = read("../matlab_example/imgs/0401.tif") #tf_rotate = transform.SimilarityTransform(rotation=np.deg2rad(30)) #img = transform.warp(img, tf_rotate) #tf_shift = transform.SimilarityTransform(translation=[60, 60]) #img = transform.warp(img, tf_shift) show(img, cmap='gray') fft2 = np.fft.fft2(img) show(np.abs(fft2), cmap='gray') shift2center = np.fft.fftshift(fft2) show(np.abs(fft2), cmap='gray') log_fft2 = np.log(1 + np.abs(fft2)) show(np.abs(log_fft2), cmap='gray') log_shift2center = np.log(1 + np.abs(shift2center)) show(np.abs(log_shift2center), cmap='gray')
# coding: utf-8 import matplotlib import matplotlib.pyplot as plt import numpy as np from skimage import io, util from skimage import data from scipy.ndimage import convolve, laplace, sobel from scipy.signal import medfilt from demo import read, show I = read('imgs/lenna.tif') show(I, 'raw_image', 'gray') # apply laplace filter I1 = laplace(I) show(I1, 'after applying laplace filter', 'gray') # apply a gussian filter I2 = sobel(I) show(I2, 'after applying sobel filter', 'gray')
def run(self): # return self.plasma_gpu() np = self.np w = self.width h = self.height step = 5 if not self.use_cl: half_len = self.half_len img = np.empty((self.width, self.height, 3), dtype=np.uint8) denom = self.denom.next() for y in xrange(0, self.height): for x in xrange(0, self.width): col = int(half_len + ( half_len * np.sin(np.sqrt((x - w / 2.0) **2 + (y - h / 2.0) **2) / denom))) if col + self.step < len(self.cols): img[x][y] = self.cols[(col + self.step)] else: img[x][y] = self.cols[len(self.cols) - (col + self.step)] else: img = self.plasma_gpu() self.step += step self.step %= len(self.cols) return img if __name__ == "__main__": from demo import show show(Runner, fps=90, rows=1000, cols=2000, scale=1)
if self.facing: col1, col2 = [ self.colors[self.np.random.choice(self.colors.shape[0], self.board_dimensions[0] / 2, replace=False)] for _ in [1, 2] ] col1.sort(0) col2.sort(0) if self.face_in: col = self.np.concatenate([col1[::-1], col2]) else: col = self.np.concatenate([col1, col2[::-1]]) else: col = self.colors[self.np.random.choice(self.colors.shape[0], self.board_dimensions[0], replace=False)] for idx, i in enumerate(col): self.pixels[idx][0] = i if not self.facing and self.sorted: self.pixels.sort(0) return self.pixels if __name__ == "__main__": from demo import show show(Runner)
# sky = [206, 237, 255] sky = next(self.sky_colours) pixels = np.full((self.dims[0], self.dims[1], 3), water, dtype=np.uint8) pixels[:, 0:13] = sky self.update_things() for thing in self.things + self.current_players.values(): template = self.things_templates[thing['type']] if thing['type'] == 'boat': colour = thing['colour'] else: colour = template['colours'] grid = template['template'] xpos = thing['xpos'] ypos = thing['ypos'] for y, row in enumerate(grid): y = np.int(np.floor(ypos + y)) for x, pix in enumerate(row): if pix != 0: col = colour[pix - 1] x = np.int((xpos + x) % self.dims[0]) pixels[x, y] = col return pixels if __name__ == "__main__": from demo import show show(Runner, fps=30, rows=17, cols=165, scale=8)
self.colors = np.random.randint(0, 255, [9012, 3]) self.pixels = self.np.zeros((self.board_dimensions[0], self.board_dimensions[1], 3)).astype(self.np.uint8) def run(self): # shift everything to the left, put a new random column on the end self.pixels = self.np.roll(self.pixels, 1, 1) if self.facing: col1, col2 = [self.colors[self.np.random.choice(self.colors.shape[0], self.board_dimensions[0]/2, replace=False)] for _ in [1,2]] col1.sort(0) col2.sort(0) if self.face_in: col = self.np.concatenate([col1[::-1],col2]) else: col = self.np.concatenate([col1,col2[::-1]]) else: col = self.colors[self.np.random.choice(self.colors.shape[0], self.board_dimensions[0], replace=False)] for idx, i in enumerate(col): self.pixels[idx][0] = i if not self.facing and self.sorted: self.pixels.sort(0) return self.pixels if __name__ == "__main__": from demo import show show(Runner)
'dlObject': 'TON_T1_G.42', 'lbWeeks': 't', 'lbDays': '1-7;1;2;3;4;5;6;7', 'dlPeriod': '1-34;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;', 'RadioType': 'flinders_location_list;cyon_reports_list_url;dummy', 'bGetTimetable': 'View Timetable', } for hidden_input in BeautifulSoup(full_day_soup, 'html.parser').find_all('input', {'type': 'hidden'}): tt_data[hidden_input['name']] = hidden_input['value'] now = datetime.now() tt_text = s.post(default_url, data=tt_data).text soup = BeautifulSoup(tt_text, 'html.parser') rows = soup.find('tbody').find_all('tr') for row in rows: cells = row.find_all('td') day = int(cells[2].p.text) title = cells[1].text if day != now.weekday(): continue time_start = int(cells[3].p.text.split(':')[0]) time_end = int(cells[4].p.text.split(':')[0]) if time_start <= now.hour < time_end: return " {} - {}:00 to {}:00 ".format(title, time_start, time_end) return "Hello!" if __name__ == "__main__": from demo import show show(Runner, fps=24)
# <h1>Video Streaming Demonstration</h1> # <img id="bg" src="/video_feed"> # </body> # </html> # """ # # # def gen(camera): # while 1: # frame = camera.run(None)[0] # frame = cv2.cvtColor(np.flipud(np.rot90(frame)), cv2.COLOR_RGB2BGR) # # jpeg = cv2.imencode('.jpg', frame)[1] # # print jpeg # yield (b'--frame\r\n' # b'Content-Type: image/jpeg\r\n\r\n' + jpeg.tobytes() + b'\r\n\r\n') # # # @app.route('/video_feed') # def video_feed(): # return Response(gen(Runner([480, 640])), # mimetype='multipart/x-mixed-replace; boundary=frame') # if __name__ == "__main__": # app.run(host='0.0.0.0', debug=True) from demo import show show(Runner, fps=30, rows=480, cols=640, scale=2, withArgs=True) # show(Runner, fps=30, rows=17, cols=165, scale=9, withArgs=True)
# coding: utf-8 import matplotlib import matplotlib.pyplot as plt import numpy as np from skimage import io, util from skimage import data from scipy.ndimage import convolve from scipy.signal import medfilt from demo import read, show I = read('imgs/Fig0219.tif') show(I, 'raw_image', 'gray') # add random noisy I1 = util.random_noise(I, mode='gaussian') show(I1, 'after adding noisy', 'gray') # apply a median filter I2 = medfilt(I1) show(I2, 'using median filter', 'gray')
# coding: utf-8 import matplotlib import matplotlib.pyplot as plt import numpy as np from skimage import io from skimage import data from scipy.ndimage import convolve from demo import read, show I = read('imgs/Fig0216.tif') show(I, 'raw_image') # get a filter f = np.ones((31, 31)) # nearest is same as replicate in matlab I1 = convolve(I, f, mode='nearest') I2 = convolve(I, f, mode='mirror') I3 = convolve(I, f, mode='constant', cval=0) show(I1, 'using nearest padding') show(I2, 'using mirror padding') show(I3, 'using constant 0 padding')
import numpy as np from demo import read, show from scipy.misc import imread, imresize, imsave img = read("../matlab_example/imgs/0401.tif") img = imresize(img, (32, 32)) show(img, cmap='gray') h, w = img.shape # 生成一个同样大小的复数矩阵 F = np.zeros([h, w], 'complex128') for u in range(h): for v in range(w): res = 0 for x in range(h): for y in range(w): res += img[x, y] * np.exp(-1.j * 2 * np.pi * (u * x / h + v * y / w)) F[u, v] = res log_F = np.log(1 + np.abs(F)) show(np.abs(log_F), cmap='gray')
# coding: utf-8 import matplotlib import matplotlib.pyplot as plt import numpy as np from skimage import io, util from skimage import data from scipy.ndimage import convolve from scipy.signal import medfilt from demo import read, show I = read('imgs/Fig0219.tif') show(I, 'raw_image', 'gray') # get an average filter r = 10 f = np.full((r, r), 1 / r**2) I1 = convolve(I, f) show(I1, 'after applying average filter', 'gray') def matlab_style_gauss2D(shape=(3, 3), sigma=0.5): """ 2D gaussian mask - should give the same result as MATLAB's fspecial('gaussian',[shape],[sigma]) """ m, n = [(ss - 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x + y * y) / (2. * sigma * sigma)) h[h < np.finfo(h.dtype).eps * h.max()] = 0
import numpy as np from demo import read, show raw_img = read("../matlab_example/imgs/0402.tif") img = np.pad(raw_img, ((0, raw_img.shape[0]), (0, raw_img.shape[1])), 'constant') show(img, cmap='gray') fft2 = np.fft.fft2(img) shift2center = np.fft.fftshift(fft2) show(np.log(1 + np.abs(shift2center)), cmap='gray') def dftuv(m, n): u = np.array(list(range(0, m))) v = np.array(list(range(0, n))) u[m // 2:] -= m v[n // 2:] -= n u, v = np.meshgrid(u, v) return u**2 + v**2 sigma = 0.05 * img.shape[0] d = dftuv(img.shape[0], img.shape[1]) h = np.exp(-d / (2 * (sigma**2))) res = np.fft.fft2(raw_img, (img.shape[0], img.shape[1])) * h res = np.fft.ifft2(res) show(np.abs(res), cmap='gray')
import urllib print("Downloading font") urllib.urlretrieve('https://www.dropbox.com/s/adt959l9bx0ojlj/slkscr.ttf?dl=1', 'slkscr.ttf') self.fnt = Font('slkscr.ttf', 16) def run(self): np = self.np now = self.dt.now() if now.minute != self.minute: self.np.random.shuffle(self.order) self.minute = now.minute message = now.strftime("%H:%M:%S") render = self.fnt.render_text(message) message = str(render).splitlines() pixels = np.zeros((self.height, max(self.width, render.width), 3), dtype=np.uint8) numcols = self.cols.shape[0] color = [(now.hour/24.*255, now.minute/60.*255, now.second/60. * 255)[i] for i in self.order] # color = [255,255,255] pad = 45 #self.width/2 - len(message[0])/2 for y in range(render.height): for x in range(render.width): if message[y][x] == '#': pixels[y+3, x+pad] = color return np.flipud(np.rot90(pixels, 1)) if __name__ == "__main__": from demo import show show(Runner, fps=30, rows=17, cols=165, scale=8)
for i in xrange(self.regions): d = np.hypot(self.points[i][0] - x, self.points[i][1] - y) if d < dmin: dmin = d h = i im[x][y] = self.cols[h] return im def run(self): np = self.np # jitter = np.random.randint(0, 3, size=self.points.shape, dtype=np.int16) - 1 xjitter = np.random.normal(1, 2, size=self.points.shape[0]).astype(dtype=np.int16) yjitter = np.random.normal(0, 1, size=self.points.shape[0]).astype(dtype=np.int16) self.points[:, 0] += xjitter self.points[:, 1] += yjitter self.points[:, 0] %= self.width self.points[:, 1] %= self.height if self.use_cl: out = self.voronoi_gpu() for p in self.points: out[p[0], p[1]] = self.lut[-1] return out return self.rand_voronoi() if __name__ == "__main__": from demo import show # fps is 1/3 so that we get 3 seconds to admire the output before changing show(Runner, fps=60, cols=900, rows=900, scale=1)