contrib 패키지를 설치해주면 해결!

오늘자 기준으로 한 63MB 정도 된다. 꽤나 큰 편 인 듯

$ python3 depth.py 
Traceback (most recent call last):
  File "/home/minimonk/src/DisparityMapfromStereoPair/depth.py", line 17, in <module>
    right_matcher = cv.ximgproc.createRightMatcher(left_matcher);
AttributeError: module 'cv2' has no attribute 'ximgproc'

$ pip install opencv-contrib-python

[링크 : https://stackoverflow.com/questions/57427233/module-cv2-cv2-has-no-attribute-ximgproc]

'Programming > python(파이썬)' 카테고리의 다른 글

cv2.stereoBM + WLS  (0) 2024.02.28
matplotlib animation  (0) 2024.02.28
pip 패키지 관리  (0) 2024.02.27
pyhthon numpy 생략없이 출력  (0) 2024.02.26
matplotlib grayscale image to 3d graph  (0) 2024.02.22
Posted by 구차니

matplotlib을 3d로 그려보는 것 까지 통합완료. 이제 SGBM만 해보면 될 듯

WLS 필터 미적용 WLS 필터 적용

 

 

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
imgL = cv.imread('tsukuba_l.png', cv.IMREAD_GRAYSCALE)
imgR = cv.imread('tsukuba_r.png', cv.IMREAD_GRAYSCALE)
max_disparity=16
stereo = cv.StereoBM_create(max_disparity, blockSize=15)
disparity = stereo.compute(imgL,imgR)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# X, Y 좌표 생성
height, width = imgL.shape
x = np.arange(0, width, 1)
y = np.arange(0, height, 1)
x, y = np.meshgrid(x, y)

# 깊이 맵을 사용하여 Z 좌표 생성
z = disparity

# 3D 그래프에 표시
ax.plot_surface(x, y, z, cmap='viridis')

plt.show()

# WLS 필터 적용
right_matcher = cv.ximgproc.createRightMatcher(stereo);
left_disp = stereo.compute(imgL, imgR);
right_disp = right_matcher.compute(imgR, imgL);

# Now create DisparityWLSFilter
wls_filter = cv.ximgproc.createDisparityWLSFilter(stereo);

sigma = 1.5
lmbda = 8000.0

wls_filter.setLambda(lmbda);
wls_filter.setSigmaColor(sigma);
filtered_disp = wls_filter.filter(left_disp, imgL, disparity_map_right=right_disp);

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

z = filtered_disp

# 3D 그래프에 표시
ax.plot_surface(x, y, z, cmap='viridis')

plt.show()

 

'Programming > python(파이썬)' 카테고리의 다른 글

cv2.ximgproc 없을 경우  (0) 2024.02.28
matplotlib animation  (0) 2024.02.28
pip 패키지 관리  (0) 2024.02.27
pyhthon numpy 생략없이 출력  (0) 2024.02.26
matplotlib grayscale image to 3d graph  (0) 2024.02.22
Posted by 구차니

 

 

[링크 : https://matplotlib.org/stable/api/animation_api.html]

 

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

[링크 : https://pythonprogramming.net/python-matplotlib-live-updating-graphs/]

[링크 : https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-loop]

 

+ 2024.03.14

import cv2
import matplotlib.pyplot as plt

def grab_frame(cap):
    ret,frame = cap.read()
    return cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)

#Initiate the two cameras
cap1 = cv2.VideoCapture(0)
cap2 = cv2.VideoCapture(1)

#create two subplots
ax1 = plt.subplot(1,2,1)
ax2 = plt.subplot(1,2,2)

#create two image plots
im1 = ax1.imshow(grab_frame(cap1))
im2 = ax2.imshow(grab_frame(cap2))

plt.ion()

while True:
    im1.set_data(grab_frame(cap1))
    im2.set_data(grab_frame(cap2))
    plt.pause(0.2)

plt.ioff() # due to infinite loop, this gets never called.
plt.show()

[링크 : https://stackoverflow.com/questions/44598124/update-frame-in-matplotlib-with-live-camera-preview]

 

matplotlib.pyplot.ion()[source]
Enable interactive mode.

See pyplot.isinteractive for more details.

See also

ioff
Disable interactive mode.

isinteractive
Whether interactive mode is enabled.

show
Show all figures (and maybe block).

pause
Show all figures, and block for a time.

[링크 : https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.ion.html]

'Programming > python(파이썬)' 카테고리의 다른 글

cv2.ximgproc 없을 경우  (0) 2024.02.28
cv2.stereoBM + WLS  (0) 2024.02.28
pip 패키지 관리  (0) 2024.02.27
pyhthon numpy 생략없이 출력  (0) 2024.02.26
matplotlib grayscale image to 3d graph  (0) 2024.02.22
Posted by 구차니

pip도 아래 명령들을 이용하면 현재 패키지 버전들을 저정하고, 필요한 버전들을 설치할 수 있다.

python 프로젝트들이 나중에 버전이 꼬여서 난리나는거 보면

필수적인데 왜 다들 안쓸까..

 

pip list
pip freeze > requirements.txt

[링크 : https://intelloper.tistory.com/53]

 

pip install -r requirements.txt

[링크 : https://itholic.github.io/python-requirements/]

'Programming > python(파이썬)' 카테고리의 다른 글

cv2.stereoBM + WLS  (0) 2024.02.28
matplotlib animation  (0) 2024.02.28
pyhthon numpy 생략없이 출력  (0) 2024.02.26
matplotlib grayscale image to 3d graph  (0) 2024.02.22
python tcp 서버 예제  (0) 2024.01.22
Posted by 구차니
Programming/openCV2024. 2. 26. 19:00

Weighted Least Squares filter라는게 sgbm 예제를 찾다가 나옴

[링크 : https://docs.opencv.org/3.4/d9/d51/classcv_1_1ximgproc_1_1DisparityWLSFilter.html]

 

필터라는 이름 답게

왼쪽의 노이즈가 심해 보이는 깊이 정보를, 면 단위로 정렬해서 보기 쉽게 변환해준다.

[링크 : https://forum.opencv.org/t/bad-disparity-map-with-sgbm-algorithm/8209]

[링크 : https://stackoverflow.com/questions/62627109/how-do-you-use-opencvs-disparitywlsfilter-in-python]

 

[링크  : https://amroamroamro.github.io/mexopencv/opencv_contrib/disparity_filtering_demo.html]

 

+

BM(block match) 알고리즘에 filter 적용 예제

[링크 : https://docs.opencv.org/4.x/d3/d14/tutorial_ximgproc_disparity_filtering.html]

 

 

 

+

2024.02.28

WLS 필터는 별도의 패키지를 설치해야 한다

$ pip install opencv-contrib-python

 

패키지 설치 후에 처리해보면 확실히 좀 더 나은 느낌이긴 하다.

BM 에 적용해봤으니 이제 SGBM 에도 해봐야..

WLS 필터 적용 전 WLS 필터 적용 후

 

$ cat depth.py 
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
imgL = cv.imread('tsukuba_l.png', cv.IMREAD_GRAYSCALE)
imgR = cv.imread('tsukuba_r.png', cv.IMREAD_GRAYSCALE)
max_disparity=16
stereo = cv.StereoBM_create(max_disparity, blockSize=15)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity)
plt.show()

right_matcher = cv.ximgproc.createRightMatcher(stereo);
left_disp = stereo.compute(imgL, imgR);
right_disp = right_matcher.compute(imgR, imgL);

# Now create DisparityWLSFilter
wls_filter = cv.ximgproc.createDisparityWLSFilter(stereo);

sigma = 1.5
lmbda = 8000.0

wls_filter.setLambda(lmbda);
wls_filter.setSigmaColor(sigma);

filtered_disp = wls_filter.filter(left_disp, imgL, disparity_map_right=right_disp);
plt.imshow(filtered_disp)
plt.show()
Posted by 구차니
Programming/openCV2024. 2. 26. 18:57

SGBM이나 BM이나 간단하게 쓰려면 인자가 크게 변하지 않는 느낌이긴 한데.. 돌려봐야 알 듯.

max_disparity = 128
stereoProcessor = cv2.StereoSGBM_create(0, max_disparity, 21)

 

depth map을 아래와 같이 변환하면 되나?

    if (apply_colourmap):
        disparity_colour_mapped = cv2.applyColorMap((disparity_scaled * (256. / max_disparity)).astype(np.uint8),
                                                                                     cv2.COLORMAP_HOT)
        cv2.imshow(window_nameD, disparity_colour_mapped)
    else:
        cv2.imshow(window_nameD, (disparity_scaled * (256. / max_disparity)).astype(np.uint8))

[링크 : https://github.com/tobybreckon/python-examples-cv/blob/master/stereo_sgbm.py]

 

+

2024.02.28

 

 

어찌어찌 변환은 완료. cv.threshold 라는 함수를 이용해서 맵을 만들고 막 변환하긴 하는데

솔찍히 멀 어떻게 변환한건진 좀더  봐야 할 듯. 근데 이거 말고도 matplotlib 에서 animation 기능으로 갱신이 가능하다고 하니

그걸 이용해봐도 될 듯.

$ cat depth.py 
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
imgL = cv.imread('tsukuba_l.png', cv.IMREAD_GRAYSCALE)
imgR = cv.imread('tsukuba_r.png', cv.IMREAD_GRAYSCALE)
max_disparity=16
stereo = cv.StereoBM_create(max_disparity, blockSize=15)
disparity = stereo.compute(imgL,imgR)
#plt.imshow(disparity,'gray')
#plt.show()
#cv.imshow("depth map", (disparity * (256/16)).astype(np.uint8))
_, disparity = cv.threshold(disparity, 0, max_disparity * 16, cv.THRESH_TOZERO)
disparity_scaled = (disparity / 16.).astype(np.uint8)
disparity_colour_mapped = cv.applyColorMap((disparity_scaled * (256. / max_disparity)).astype(np.uint8),cv.COLORMAP_HOT)
cv.imshow("depth map", disparity_colour_mapped)

cv.waitKey()
Posted by 구차니

먼가 쓸데없이 복잡해서 외우고 쓰진 못할 듯 -_ㅠ

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)

[링크 : https://stackoverflow.com/questions/1987694/how-do-i-print-the-full-numpy-array-without-truncation]

'Programming > python(파이썬)' 카테고리의 다른 글

matplotlib animation  (0) 2024.02.28
pip 패키지 관리  (0) 2024.02.27
matplotlib grayscale image to 3d graph  (0) 2024.02.22
python tcp 서버 예제  (0) 2024.01.22
파이썬 소켓 예제  (0) 2024.01.17
Posted by 구차니
Programming/openCV2024. 2. 24. 23:00

얼마전 테스트 해본 계산 알고리즘은 BM(block match)인데 먼가 먼 곳은 전혀 안 잡아줘서

어떻게 설정을 해야 하나 패러미터를 찾아보고 있었는데 다른 알고리즘이 있다는걸 발견함.

 

 

numDisparities는 검색할 범위. 16의 배수로 하라는데, 해보면 화면의 왼쪽이 사라진다. 지정된 숫자만큼 가장 왼쪽은 버려지는 듯

blockSize. 동일한 블록으로 연산할 단위라고 해야하나. 해당 숫자가 NxN으로 되는건지 숫자가 커지면 블럭이 거칠어 지는 느낌.

numDisparities
the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to numDisparities. The search range can then be shifted by changing the minimum disparity.

blockSize
the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence.

[링크 : https://docs.opencv.org/4.x/d9/dba/classcv_1_1StereoBM.html]

[링크 : https://makepluscode.tistory.com/108]

 

BM 방법은 실내에서나 쓰는거지 실외에서는 잘 안 맞다고 그러니 SGM 기반으로 된 걸 써라~ 인가.

Wrong method. BM is only meant for simple indoor use with low dynamic measuring range. With indoor image, you just need a adjsut mindisp and number of disp and window size.

For outdoor, it is more complex. Maybe u just start. BM and other global based method has the poor result. Either disfigured for overfitting, or streaking effect due to local similarity error.

Current state of the art for traditional CV is the SGM based method proposed by HH. And for the deep learning-based method, there is no best case, vary from case to case/dataset to dataset. The work from lecun Žbontar "Stereo Matching by Training a Convolutional Neural Network " is sth that I used for comparison often.

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

 

별별 희한한 알고리즘이 나온다. SGBM? BM 이 붙긴한데..

            alg = strcmp(_alg, "bm") == 0 ? STEREO_BM :
                  strcmp(_alg, "sgbm") == 0 ? STEREO_SGBM :
                  strcmp(_alg, "hh") == 0 ? STEREO_HH :
                  strcmp(_alg, "var") == 0 ? STEREO_VAR : -1;

[링크 : https://copyprogramming.com/howto/opencv-stereo-matching]

 

[링크 : https://docs.opencv.org/4.9.0/d9/dba/classcv_1_1StereoBM.html]

[링크 : https://docs.opencv.org/4.9.0/d2/d85/classcv_1_1StereoSGBM.html]

 

 

SGBM

semi-global block matching algorithm

[링크 : https://amroamroamro.github.io/mexopencv/matlab/cv.StereoSGBM.html]

 

+

2024.02.26

요 근래 버전이긴 한데 오래된 버전에서도 나오긴 하고 python엣도 SGBM이 있으니, 테스트는 해봐야 할 듯.

>>> import cv2>>> cv2.stereo
cv2.stereo                         cv2.stereoRectifyUncalibrated(
cv2.stereoCalibrate(               cv2.stereo_MatchQuasiDense(
cv2.stereoCalibrateExtended(       cv2.stereo_PropagationParameters(
cv2.stereoRectify(                 cv2.stereo_QuasiDenseStereo(

>>> cv2.St
cv2.StereoBM(
cv2.StereoBM_PREFILTER_NORMALIZED_RESPONSE
cv2.StereoBM_PREFILTER_XSOBEL
cv2.StereoBM_create(
cv2.StereoMatcher(
cv2.StereoMatcher_DISP_SCALE
cv2.StereoMatcher_DISP_SHIFT
cv2.StereoSGBM(
cv2.StereoSGBM_MODE_HH
cv2.StereoSGBM_MODE_HH4
cv2.StereoSGBM_MODE_SGBM
cv2.StereoSGBM_MODE_SGBM_3WAY
cv2.StereoSGBM_create(
cv2.Stitcher(
cv2.Stitcher_ERR_CAMERA_PARAMS_ADJUST_FAIL
cv2.Stitcher_ERR_HOMOGRAPHY_EST_FAIL
cv2.Stitcher_ERR_NEED_MORE_IMGS
cv2.Stitcher_OK
cv2.Stitcher_PANORAMA
cv2.Stitcher_SCANS
cv2.Stitcher_create(

 

The definitions of all the arguments are given at the bottom of the documentation page here
In block matching or cv2.StereoBM_create() the disparity is computed by comparing the sum of absolute differences (SAD) of each 'block' of pixels. In semi-global block matching or cv2.StereoSGBM_create() forces similar disparity on neighbouring blocks. This creates a more complete disparity map but is more computationally expensive.
Paper that discusses 'block matching'
Paper that discusses 'semi-global block matching'

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

Posted by 구차니

matplotlib을 이용하여 lena를 3d로 그리는게 보이길래 해보려는데

아래와 같이 deprecated 경고만 발생해서 되는걸 못 찾다가

>>> ax = fig.gca(projection='3d')
<stdin>:1: MatplotlibDeprecationWarning: Calling gca() with keyword arguments was deprecated in Matplotlib 3.4. Starting two minor releases later, gca() will take no keyword arguments. The gca() function should only be used to get the current axes, or if no axes exist, create new axes with default keyword arguments. To create a new axes with non-default arguments, use plt.axes() or plt.subplot().

>>> ax= Axes3D(fig)
<stdin>:1: MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure is deprecated since 3.4. Pass the keyword argument auto_add_to_figure=False and use fig.add_axes(ax) to suppress this warning. The default value of auto_add_to_figure will change to False in mpl3.5 and True values will no longer work in 3.6.  This is consistent with other Axes classes.

 

chatGPT에게 물어보니 아래와 같이 줘서 시도하니 나오긴 나온다.

import cv2
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 이미지 읽기
image_path = 't.png'
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# 이미지의 높이와 너비 얻기
height, width = img.shape

# 2D 배열을 생성하여 각 픽셀의 깊이 값을 저장
depth_map = np.zeros_like(img, dtype=np.float32)

# 각 픽셀의 깊이 계산 (여기서는 그레이스케일 값으로 대체)
depth_map = img.astype(np.float32)

# 3D 그래프 생성
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# X, Y 좌표 생성
x = np.arange(0, width, 1)
y = np.arange(0, height, 1)
x, y = np.meshgrid(x, y)

# 깊이 맵을 사용하여 Z 좌표 생성
z = depth_map

# 3D 그래프에 표시
ax.plot_surface(x, y, z, cmap='viridis')

# 그래프 표시
plt.show()

 

분위기를 보아하니 viridis 를 해서 저런 녹색톤이 나오는것 같은데 plasms가 웬지 flir에서 보던 느런 느낌이려나?

[링크 : https://matplotlib.org/stable/users/explain/colors/colormaps.html]

 

 

위에서 보면 아래와 같이 lena 이미지가 똭!

[링크 : https://stackoverflow.com/questions/31805560/how-to-create-surface-plot-from-greyscale-image-with-matplotlib]

[링크 : https://jehyunlee.github.io/2021/07/10/Python-DS-80-mpl3d2/]

 

 

'Programming > python(파이썬)' 카테고리의 다른 글

pip 패키지 관리  (0) 2024.02.27
pyhthon numpy 생략없이 출력  (0) 2024.02.26
python tcp 서버 예제  (0) 2024.01.22
파이썬 소켓 예제  (0) 2024.01.17
ipython notebook -> jupyter notebook  (0) 2024.01.11
Posted by 구차니
Programming/openCV2024. 2. 21. 23:52

이미지는 아래 github에서 받으면 될 듯.

[링크 : https://github.com/canberkgurel/DisparityMapfromStereoPair]

 

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
imgL = cv.imread('my_photo-1.jpg', cv.IMREAD_GRAYSCALE)
imgR = cv.imread('my_photo-2.jpg', cv.IMREAD_GRAYSCALE)
stereo = cv.StereoBM_create(numDisparities=16, blockSize=5)
disparity = stereo.compute(imgL,imgR)
plt.imshow(disparity,'gray')
plt.show()

[링크 : https://docs.opencv.org/3.4/dd/d53/tutorial_py_depthmap.html]

 

blockSize는 홀수여야 한다고 한다

[링크 : https://makepluscode.tistory.com/108]

 

웹캠을 조금 옆으로 보내 찍고 대충 먼가 인식 가능하게 숫자 적절하게 맞춰서 해보았는데

안경만 도드라지는 느낌..

왼쪽은 16에 5

오른쪽은 16과 7로 설정. 

+

2024.02.23

 

아래 이미지를 이용해서 3d 계산하고

[링크 : https://github.com/canberkgurel/DisparityMapfromStereoPair]

 

나온 depth map을 저장하고

 

depth 맵을 3d 이미지로 변환하면

멀 잘못 만들어 줬는지 z 축과 x 축이 뒤바뀡 모양

아무튼 두상과 램프 스탠드가 깊이로 인식된 것이 보인다.

 

Posted by 구차니