Python, Basic認証情報の入ったURLをURLと認証情報に分けるために書いたけどrequestsがもとからこの機能持ってたのでいらなくなったスニペット

https://gist.github.com/aoirint/ddbc49898d39cc0faa15765db8aa247a

2022年5月22日 · aoirint

PsychopyでOpenCV画像をImageStimで表示する

Psychopy - GitHub y軸反転と画素値をfloat(0-1)に変換すればOK。 npimg: np.ndarray # (height, width, num_channels) stimimg = np.flip(npimg.astype(np.float32) / 255, axis=0) ウインドウに表示させるサンプル import numpy as np # numpy>=1.20.1 import cv2 # type: ignore # opencv-python>=4.5.1.48 from psychopy import core # type: ignore # psychopy>=2020.2.10 from psychopy.visual import Window, ImageStim # type: ignore import sys # npimg: np.ndarray = cv2.imread('image.png', 1) npimg: np.ndarray = np.zeros((400, 400, 3), dtype=np.uint8) npimg = cv2.line(npimg, (0, 50), (400, 50), (127, 127, 127), 3) npimg = cv2.line(npimg, (50, 0), (50, 400), (255, 255, 255), 3) # cv2.imwrite('image.png', npimg) stimimg = np.flip(npimg.astype(np.float32) / 255, axis=0) window = Window((400, 400), color='black', units='pix') stim = ImageStim(window, pos=(0, 0), size=(400, 400)) stim.image = stimimg stim.draw() window.flip() core.wait(3) # while True: # stim.draw() # window.flip() # # for keys in event.getKeys(timeStamped=True): # if keys[0] in [ 'escape', 'q' ]: # sys.exit(0) # # core.wait(0.01)

2021年2月14日 · aoirint

Sphinx

Python製のドキュメント生成ツール。 Python 3.8.5 Sphinx 3.4.2 Sphinx · PyPI pip3 install Sphinx reST(reStructuredText) SphinxではデフォルトでreStructuredTextというマークアップ言語を使う。 https://www.sphinx-doc.org/ja/master/usage/restructuredtext/basics.html https://atom.io/packages/language-restructuredtext 既存Pythonプロジェクトにドキュメントを追加する setup.py などが存在するPyPIパッケージプロジェクトを想定する。 プロジェクトのルートに docs ディレクトリを作成し、 インタラクティブツール sphinx-quickstart を実行する。 mkdir docs cd docs/ sphinx-quickstart Separate source and build directories (y/n) と聞かれるので、 y 。 プロジェクト名、著者名、言語などを答える。 source ディレクトリ、 build ディレクトリ、 Makefile が生成される。 make html 以上のコマンドで build/html ディレクトリにHTMLが生成される。 python3 -m http.server -b localhost -d build/html などで確認する。 次はPythonモジュールのdocstringからドキュメントを自動生成する。 Sphinx でPythonのAPIドキュメントを自動作成 - Qiita python書くなら絶対に使いたい2つのドキュメント生成ツール - Qiita #!/bin/bash SCRIPT_DIR=$(cd $(dirname $0); pwd) cd "${SCRIPT_DIR}" sphinx-apidoc -f -o "./source/api" "../mymodule" make html docs/mkdocs.sh を以上のように作成し、実行する(TODO:Makefileへの入れ込み)。 ここでは、以下のように docs ディレクトリと並んで、パッケージとして提供するPythonモジュール mymodule のディレクトリがあることを想定している。 なお、 docs/source/conf.py は設定ファイルであり、 例えば html_theme = 'sphinx_rtd_theme' のような設定を追加し、 pip3 install sphinx-rtd-theme してから make html することで、Read the Docsスタイルのドキュメントを生成できる。 ...

2021年1月5日 · aoirint

Pythonを追加するDockerfile

pyenvは部品を使うだけで最終的には削除します(Pythonは/usr/localに導入) FROM ubuntu:bionic ARG DEBIAN_FRONTEND=noninteractive ARG PYTHON_VERSION=3.9.0 ARG PYTHON_ROOT=/usr/local ARG PYENV_ROOT=/tmp/.pyenv ARG PYBUILD_ROOT=/tmp/python-build RUN apt update && apt install -y \ build-essential \ libssl-dev \ zlib1g-dev \ libbz2-dev \ libreadline-dev \ libsqlite3-dev \ wget \ curl \ llvm \ libncurses5-dev \ libncursesw5-dev \ xz-utils \ tk-dev \ libffi-dev \ liblzma-dev \ python-openssl \ git \ && git clone https://github.com/pyenv/pyenv.git $PYENV_ROOT \ && PREFIX=$PYBUILD_ROOT $PYENV_ROOT/plugins/python-build/install.sh \ && $PYBUILD_ROOT/bin/python-build -v $PYTHON_VERSION $PYTHON_ROOT \ && rm -rf $PYBUILD_ROOT $PYENV_ROOT

2020年12月8日 · aoirint

Ubuntu, pyenv環境でtkinterを使う

sudo apt install tk-dev python-tk python3-tk pyenv install 3.8.6 pyenv global 3.8.6 python3 -m tkinter

2020年10月4日 · aoirint

Python Requests

ses = requests.Session() Headers ses.headers.update({ }) Copy cookies from Selenium ses.cookies.clear() for cookie in driver.get_cookies(): rc = requests.cookies.create_cookie(domain=cookie['domain'], name=cookie['name'], value=cookie['value']) ses.cookies.set_cookie(rc) Download a file file_url: str dest_path: str with tempfile.NamedTemporaryFile() as fp: with ses.get(file_url, stream=True) as r: r.raise_for_status() for chunk in r.iter_content(chunk_size=8192): fp.write(chunk) fp.flush() shutil.copy(fp.name, dest_path)

2020年9月28日 · aoirint

docker-composeによるPython + Selenium環境

2022-08-06 追記 Seleniumのバージョンが上がって一部非推奨化したりしたので、そちらに対応した版を作成しました。 リポジトリ: https://github.com/aoirint/compose-selenium-python-template 2020-09-28 docker-compose.yml version: '3.8' services: app: build: ./app/ entrypoint: [ "wait-for-it", "selenium:4444", "--", "python3", "/code/main.py" ] volumes: - ./work:/work environment: SELENIUM_URL: http://selenium:4444/wd/hub depends_on: - selenium selenium: image: selenium/standalone-chrome volumes: - /dev/shm:/dev/shm app/Dockerfile FROM python:3 WORKDIR /work RUN apt update && apt install -y \ wait-for-it ADD requirements.txt /tmp/ RUN pip3 install -r /tmp/requirements.txt ADD code/ /code app/requirements.txt requests >= 2.24.0 selenium app/code/main.py from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.desired_capabilities import DesiredCapabilities selenium_url = os.environ['SELENIUM_URL'] website_url: str = None driver = webdriver.Remote( command_executor=selenium_url, desired_capabilities=DesiredCapabilities.CHROME, ) driver.get(website_url)

2020年9月28日 · aoirint

PyTorch pydub.AudioSegmentをtorch.Tensorに変換する

import numpy as np import torch import torchaudio import torchaudio.transforms as T ''' in: pydub.AudioSegment out: torch.Tensor (float32) ''' def to_tensor(audio): sample_width = audio.sample_width sample_bits = 8 * sample_width sample_max_int = 2 ** sample_bits sample_channels = audio.channels samples = np.asarray(audio.get_array_of_samples()) samples = samples.reshape((-1, 2)).transpose((1, 0)) # LRLR -> Channel, Samples samples = samples.astype('f') / sample_max_int samples = torch.from_numpy(samples).type(torch.float32) return samples

2020年3月26日 · aoirint

OpenGL 2.1/4.1(GLFW)でOpenCVの画像を表示する(Python, Mac)

pip3 install PyOpenGL glfw モジュールバージョン PyOpenGL==3.1.5 glfw==1.11.0 システムのOpenGLバージョン Vendor : b'Intel Inc.' GPU : b'Intel Iris OpenGL Engine' OpenGL version : b'4.1 INTEL-14.4.23' OpenGL 2.1 mcfletch/pyopengl: Repository for the PyOpenGL Project Python3で始めるOpenGL4 - CodeLabo Python GLFWでOpenGLバージョン指定とウィンドウ表示 - CodeLabo PythonでOpenCVの画像をOpenGLで表示する - Qiita Vendor : b'Intel Inc.' GPU : b'Intel Iris OpenGL Engine' OpenGL version : b'2.1 INTEL-14.4.23' glDrawPixels import cv2 from OpenGL.GL import * import glfw if __name__ == '__main__': img = cv2.imread('lena.png', 1) img_gl = cv2.cvtColor(cv2.flip(img, 0), cv2.COLOR_BGR2RGB) glfw.init() # These parameters need to be changed according to your environment. # Mac: https://support.apple.com/ja-jp/HT202823 # glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) # glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) # glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) width = img.shape[1] height = img.shape[0] window = glfw.create_window(width, height, 'Lena', None, None) glfw.make_context_current(window) print('Vendor :', glGetString(GL_VENDOR)) print('GPU :', glGetString(GL_RENDERER)) print('OpenGL version :', glGetString(GL_VERSION)) while not glfw.window_should_close(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glDrawPixels(width, height, GL_RGB, GL_UNSIGNED_BYTE, img_gl) glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate() Texture import cv2 from OpenGL.GL import * import glfw if __name__ == '__main__': img = cv2.imread('lena.png', 1) img_gl = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) glfw.init() # These parameters need to be changed according to your environment. # Mac: https://support.apple.com/ja-jp/HT202823 # glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) # glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) # glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) # glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) window = glfw.create_window(256, 256, 'Lena', None, None) glfw.make_context_current(window) print('Vendor :', glGetString(GL_VENDOR)) print('GPU :', glGetString(GL_RENDERER)) print('OpenGL version :', glGetString(GL_VERSION)) height, width = img.shape[:2] glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_gl) while not glfw.window_should_close(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glEnable(GL_TEXTURE_2D) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glBegin(GL_QUADS) glTexCoord2d(0.0, 1.0) glVertex3d(-1.0, -1.0, 0.0) glTexCoord2d(1.0, 1.0) glVertex3d(1.0, -1.0, 0.0) glTexCoord2d(1.0, 0.0) glVertex3d(1.0, 1.0, 0.0) glTexCoord2d(0.0, 0.0) glVertex3d(-1.0, 1.0, 0.0) glEnd() glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate() OpenGL 4.1 / GLSL PythonでVAOによるGLSLシェーダープログラミング! - CodeLabo Suspected fragment shader problem, No color, OpenGL 4, GLFW 3, GLEW - OpenGL / OpenGL: Basic Coding - Khronos Forums 床井研究室 - 第2回 テクスチャの割り当て Vendor : b'Intel Inc.' GPU : b'Intel Iris OpenGL Engine' OpenGL version : b'4.1 INTEL-14.4.23' import sys from OpenGL.GL import * import glfw import numpy as np import cv2 vertex_shader_text = ''' #version 410 core in vec3 vPosition; out vec2 vTextureCoord; void main(void) { vTextureCoord = vec2((vPosition.x + 1.0) / 2, (vPosition.y + 1.0) / 2); gl_Position = vec4(vPosition, 1.0); } ''' fragment_shader_text = ''' #version 410 core uniform sampler2D vTexture; in vec2 vTextureCoord; out vec4 flagColor; void main(void) { flagColor = texture(vTexture, vTextureCoord).rgba; } ''' def init_context(): print('Initializing context..') glfw.init() glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4) glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1) glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True) glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) global window window = glfw.create_window(512, 512, __file__, None, None) glfw.make_context_current(window) print('Vendor :', glGetString(GL_VENDOR)) print('GPU :', glGetString(GL_RENDERER)) print('OpenGL version :', glGetString(GL_VERSION)) def init_texture(): print('Initializing texture..') img = cv2.imread('lena.png', 1) img_gl = cv2.cvtColor(cv2.flip(img, 0), cv2.COLOR_BGR2RGB) global width, height height, width = img.shape[:2] global texture texture = glGenTextures(1) glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, texture) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_gl) def init_shader(): print('Initializing shader..') global vertex_shader vertex_shader = glCreateShader(GL_VERTEX_SHADER) glShaderSource(vertex_shader, vertex_shader_text) glCompileShader(vertex_shader) if not glGetShaderiv(vertex_shader, GL_COMPILE_STATUS): print('Vertex shader is not OK') print(glGetShaderInfoLog(vertex_shader)) sys.exit(1) else: print('Vertex shader is OK') global fragment_shader fragment_shader = glCreateShader(GL_FRAGMENT_SHADER) glShaderSource(fragment_shader, fragment_shader_text) glCompileShader(fragment_shader) if not glGetShaderiv(fragment_shader, GL_COMPILE_STATUS): print('Fragment shader is not OK') print(glGetShaderInfoLog(fragment_shader)) sys.exit(1) else: print('Fragment shader is OK') global program program = glCreateProgram() glAttachShader(program, vertex_shader) glDeleteShader(vertex_shader) glAttachShader(program, fragment_shader) glDeleteShader(fragment_shader) glLinkProgram(program) if not glGetProgramiv(program, GL_LINK_STATUS): print('Shader program is not OK') print(glGetProgramInfoLog(program)) sys.exit(1) else: print('Shader program is OK') def init_vao(): print('Initializing vao..') # anti-clockwise vertices = np.array([ -1.0, -1.0, 0.0, # left bottom 1.0, -1.0, 0.0, # right bottom -1.0, 1.0, 0.0, # left top -1.0, 1.0, 0.0, # left top 1.0, -1.0, 0.0, # right bottom 1.0, 1.0, 0.0, # right top ], dtype=np.float32) global vertex_vbo vertex_vbo = glGenBuffers(1) global vertex_vao vertex_vao = glGenVertexArrays(1) glBindVertexArray(vertex_vao) glEnableVertexAttribArray(0) glBindBuffer(GL_ARRAY_BUFFER, vertex_vbo) glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW) glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, None) glBindVertexArray(0) def render(): glUseProgram(program) glUniform1i(glGetUniformLocation(program, 'vTexture'), 0) glBindVertexArray(vertex_vao) glDrawArrays(GL_TRIANGLES, 0, 6) glBindVertexArray(0) if __name__ == '__main__': init_context() init_texture() init_shader() init_vao() print('Start rendering..') while not glfw.window_should_close(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) render() glfw.swap_buffers(window) glfw.poll_events() glfw.destroy_window(window) glfw.terminate() PyOpenGL Documentation PyOpenGL · PyPI glfw · PyPI

2020年3月23日 · aoirint

OpenCV FullScreen Window

Python - PythonのOpenCVでフルスクリーン表示|teratail import cv2 cv2.namedWindow('screen', cv2.WINDOW_NORMAL) cv2.setProperty('screen', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. python-opencvでQt plugin “cocoa"が見つからないというエラー - Qiita 黒画面 import cv2 import numpy as np # Change here WIDTH = 1920 HEIGHT = 1080 # For secondary monitor, LEFT = 0 TOP = 0 screen = np.zeros((HEIGHT, WIDTH), dtype=np.uint8) cv2.namedWindow('screen', cv2.WINDOW_NORMAL) cv2.moveWindow('screen', LEFT, TOP) cv2.setWindowProperty('screen', cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN) cv2.imshow('screen', screen) cv2.waitKey(0) For dynamic image size, ...

2020年3月20日 · aoirint