Programming/web 관련2024. 7. 19. 18:29

'Programming > web 관련' 카테고리의 다른 글

web worker  (0) 2024.07.19
mirage.js - api mockup  (0) 2024.07.19
웹 브라우저 쿠키  (0) 2024.03.27
let's encrypt 방식  (0) 2024.02.02
ajax session 인증  (0) 2024.01.26
Posted by 구차니
Programming/web 관련2024. 7. 19. 18:27

자바 스크립트의 메인 쓰레드가 아닌 브라우저의 백그라운드 쓰레드로 돌리는 기능.

탭이 비활성화 되어도 멀티 쓰레드로 작동이 된다고.

 

[링크 : https://samori.tistory.com/87]

[링크 : https://medium.com/hcleedev/web-web-worker-사용법과-주의할-점-webpack-메모리-문제-테스트-모킹-2d77c5b23afe]

'Programming > web 관련' 카테고리의 다른 글

XMLHttpRequest 가로채기  (0) 2024.07.19
mirage.js - api mockup  (0) 2024.07.19
웹 브라우저 쿠키  (0) 2024.03.27
let's encrypt 방식  (0) 2024.02.02
ajax session 인증  (0) 2024.01.26
Posted by 구차니
Programming/web 관련2024. 7. 19. 15:00

신기하게도(?) 크롬의 XMLHttpRequest 나 fetch 명령을 가로채서

서버 구동없이 클라이언트에서 api 목업을 한다고 한다.

 

네트워크로 나가지만 않을뿐 결국에는 함수의 결과물을 리턴해주는 식으로 간소화 하는건가..?

[링크 : https://miragejs.com/]

'Programming > web 관련' 카테고리의 다른 글

XMLHttpRequest 가로채기  (0) 2024.07.19
web worker  (0) 2024.07.19
웹 브라우저 쿠키  (0) 2024.03.27
let's encrypt 방식  (0) 2024.02.02
ajax session 인증  (0) 2024.01.26
Posted by 구차니
Programming/node.js2024. 7. 18. 10:58

색상을 포함한 스타일 지정 가능한 라이브러리 찾는중

예제를 봐서는 멀티시트도 지원

 

[링크 : https://www.npmjs.com/package/node-excel-export]

'Programming > node.js' 카테고리의 다른 글

web qr decoder  (0) 2024.04.04
node.js 웹소켓 채팅 서버 예제  (0) 2022.07.14
ubuntu 18.04 / nodej.s 18.x 실패  (0) 2022.05.19
웹소켓  (0) 2022.03.25
broadway / jsmpeg  (0) 2020.09.16
Posted by 구차니
Programming/chart.js2024. 6. 27. 16:35

chart.js 에서 반응형 설정은 아래와 같은데

options : {
  responsive : true,
}

[링크 : https://www.chartjs.org/docs/latest/configuration/responsive.html]

 

정작 이렇게 설정하고 보면 아래와 같이 나오는데

 

요걸 창 크기 줄여서 작게 만들고

 

다시 화면을 원래대로 키우면 그래프는 안커진다.

 

머라머라 써있는데 모르겠고

Important Note
Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example ):

<div class="chart-container" style="position: relative; height:40vh; width:80vw">
    <canvas id="chart"></canvas>
</div>
 
        Copied!
    
The chart can also be programmatically resized by modifying the container size:

chart.canvas.parentNode.style.height = '128px';
chart.canvas.parentNode.style.width = '128px';
 
        Copied!
    
Note that in order for the above code to correctly resize the chart height, the maintainAspectRatio option must also be set to false.

[링크 : https://www.chartjs.org/docs/latest/configuration/responsive.html#important-note]

 

responsive : true 하고

창의 최소 높이(css min-height)를 지정하면 그정도 까진 사단이 안난다는 의미인 듯.

[링크 : https://stackoverflow.com/questions/55545191/]

'Programming > chart.js' 카테고리의 다른 글

chart.js multi y axis  (0) 2023.09.27
chart.js 특정 항목 보이지 않게 하기(가로줄 치기)  (0) 2023.03.10
chart.js 수직 도움선  (0) 2023.01.27
Posted by 구차니

창을 figure라고 하는 것 같은데

openCV는 창을 명시하고 그릴 데이터를 지정한다면

openGL은 선택을 하고 그리는 거라 순서가 필요한데

matplotlib은 openGL 처럼 그릴곳을 선택하고 그리는 컨셉을 사용한 듯.

 

>>> plt.ion() # 인터랙티브모드 전환
<matplotlib.pyplot._IonContext object at 0x71521b249b40>
>>> plt.figure(1) # 여기서 Figure 1 이라는 창이 열림
<Figure size 640x480 with 0 Axes>
>>> plt.plot([1,2,3]) # Figure 1 창에 그래프 그려짐
[<matplotlib.lines.Line2D object at 0x7152194aead0>]
>>> plt.figure(2) # 여기서 Figure 2 이라는 창이 열림
<Figure size 640x480 with 0 Axes>
>>> plt.plot([2,3,4,5]) # Figure 2 창에 그래프 그려짐
[<matplotlib.lines.Line2D object at 0x71521a9c2410>]
>>> plt.figure(1) # UI 상으로 변동은 없으나 Figure 1 창에 그리도록 선택
<Figure size 640x480 with 1 Axes>
>>> plt.plot([2,3,4,5]) # Figure 1 창에 추가로 그려짐
[<matplotlib.lines.Line2D object at 0x71521a9eca30>]

[링크 : https://matplotlib.org/stable/gallery/subplots_axes_and_figures/multiple_figs_demo.html]

 

하나의 창 안에서 나누는건 subplot 인듯

[링크 : https://stackoverflow.com/questions/41210823/display-multiple-images-in-subplots]

Posted by 구차니

subplot을 생성하고 해도 되고

plt.plot() 으로 바로 한 것에 plt.cla() 해도 된다.

 

>>> fig, ax = plt.subplots()
>>> ax.plot([0,1,2,3,4,5])

>>> ax.clf()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'AxesSubplot' object has no attribute 'clf'. Did you mean: 'cla'?

>>> ax.cla()

[링크 : https://m.blog.naver.com/hsy2569/221814138095]

Posted by 구차니
Programming/openCV2024. 5. 23. 12:19

openCV를 파이썬에서 사용할때

highGUI를 쓰면 편하긴 한데..

cv2.imshow()를 쓰려고 하면, cv2.waitKey()를 써서 멈춰줘야만 해서 인터프리터에서 쓰기가 힘들다

 

matplotlib을 plt.ion() 으로 인터랙티브 모드 켜게 되면

matplotlib의 plot이 독립 쓰레드로 작동해서 opencv의 highGUI 처럼 멈추지 않고 작동한다.

plt.imshow()는 단순하게 이미지 포인터를 바꾸어 주고

plt.pause()를 통해 데이터를 실제 GUI에 갱신할 시간을 벌어주고

plt.show()를 통해 이미지를 업데이트 한다.

import matplotlib.pyplot as plt
import cv2

cap = cv2.VideoCapture(0)    
plt.ion()

while (True):
    ret, frame = cap.read()
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    plt.subplot(1,2,1), plt.imshow(frame, interpolation='nearest')  
    plt.pause(0.001)
    plt.show()

[링크 : https://stackoverflow.com/questions/47172219/how-can-i-use-matplotlib-in-real-time]

 

openCV가 v4l로 이미지를 획득할때는 BGR로 받고, matplotlib은 RGB로 표현하니, 위의 예제를 실행하면 사람이 스머프가 된다.

img_cv2 = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

[링크 : https://tempdev.tistory.com/32]

 

전체 코드를 보면 아래와 같이 되는데.. cv2.imshow() 보다 많이 느린 느낌.. 딱 테스트용으로만 쓸 수 있을 듯

import cv2
import matplotlib.pyplot as plt

cap = cv2.VideoCapture(0)
plt.ion()

while (True):
    ret, img = cap.read()
    data = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow(data)
    plt.pause(0.001)
    plt.show()
Posted by 구차니

linux 에서는 pulseaudio 쓰는 라이브러리가 유리하겠지?

[링크 : https://pypi.org/project/SoundCard/]

[링크 : https://soundcard.readthedocs.io/en/latest/]

 

Posted by 구차니

chatGPT 님 가라사대

재생 예제, 녹음 + fft 분석

import numpy as np
import sounddevice as sd

# 파라미터 설정
duration = 3  # 재생할 시간(초)
sampling_freq = 44100  # 샘플링 주파수 (Hz)
frequency = 440  # sine 파의 주파수 (Hz)

# 시간 배열 생성
t = np.linspace(0, duration, int(sampling_freq * duration), endpoint=False)

# sine 파 생성
sine_wave = np.sin(2 * np.pi * frequency * t)

# 사운드 재생
sd.play(sine_wave, samplerate=sampling_freq)
sd.wait()  # 재생이 끝날 때까지 대기
import numpy as np
import matplotlib.pyplot as plt
import sounddevice as sd
from scipy.fft import fft

# 녹음 파라미터 설정
duration = 5  # 녹음 시간 (초)
sampling_freq = 44100  # 샘플링 주파수 (Hz)

# 녹음 시작
print("녹음을 시작합니다...")
recorded_audio = sd.rec(int(duration * sampling_freq), samplerate=sampling_freq, channels=1)
sd.wait()  # 녹음이 끝날 때까지 대기
print("녹음이 완료되었습니다.")

# FFT를 위한 주파수 영역 생성
freq_axis = np.fft.fftfreq(len(recorded_audio), d=1/sampling_freq)

# FFT 계산
audio_fft = fft(recorded_audio.flatten())

# FFT 결과 그래프 표시
plt.figure(figsize=(10, 4))
plt.plot(freq_axis[:len(freq_axis)//2], np.abs(audio_fft)[:len(freq_axis)//2])
plt.title("FFT 분석 결과")
plt.xlabel("주파수 (Hz)")
plt.ylabel("Magnitude")
plt.grid(True)
plt.show()

[링크 : https://pypi.org/project/sounddevice/]

 

Assuming you have a NumPy array named myarray holding audio data with a sampling frequency of fs (in the most cases this will be 44100 or 48000 frames per second), you can play it back with play():
sd.play(myarray, fs)

[링크 : https://python-sounddevice.readthedocs.io/en/0.4.6/usage.html#playback]

 

duration = 10.5  # seconds
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)

[링크 : https://python-sounddevice.readthedocs.io/en/0.4.6/usage.html#recording]

 

[링크 : https://python-sounddevice.readthedocs.io/en/0.4.6/]

 

+

반복 재생

import soundfile as sf
import sounddevice as sd

weight = 1.4

data, fs = sf.read('sound.wav')
sd.play(data * weight, fs,loop=True)
sd.stop()

[링크 : https://stackoverflow.com/questions/47606214/stop-the-loop-in-sounddevice-audio-output]

Posted by 구차니