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 구차니
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 구차니
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 구차니
Programming/openCV2024. 2. 20. 19:07

스테레오 카메라를 이용해서 깊이 분석을 하기 전에 렌즈 왜곡을 먼저 잡아야 한다고 한다.

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

[링크 : http://www.gisdeveloper.co.kr/?p=6955]

 

 

캘리브레이션은 체커보드 있으면 된다는데, 어찌어찌 만들어 놓았으니 해봐야지

[링크 : https://foss4g.tistory.com/1665]

 

Calibration
Now that we have our object points and image points, we are ready to go for calibration. We can use the function, cv.calibrateCamera() which returns the camera matrix, distortion coefficients, rotation and translation vectors etc.

ret, mtx, dist, rvecs, tvecs = cv.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

Undistortion
Now, we can take an image and undistort it. OpenCV comes with two methods for doing this. However first, we can refine the camera matrix based on a free scaling parameter using cv.getOptimalNewCameraMatrix(). If the scaling parameter alpha=0, it returns undistorted image with minimum unwanted pixels. So it may even remove some pixels at image corners. If alpha=1, all pixels are retained with some extra black images. This function also returns an image ROI which can be used to crop the result.

So, we take a new image (left12.jpg in this case. That is the first image in this chapter)

img = cv.imread('left12.jpg')
h,  w = img.shape[:2]
newcameramtxroi = cv.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
1. Using cv.undistort()
This is the easiest way. Just call the function and use ROI obtained above to crop the result.

# undistort
dst = cv.undistort(img, mtx, dist, None, newcameramtx)
# crop the image
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv.imwrite('calibresult.png', dst)

2. Using remapping
This way is a little bit more difficult. First, find a mapping function from the distorted image to the undistorted image. Then use the remap function.

# undistort
mapx, mapy = cv.initUndistortRectifyMap(mtx, dist, None, newcameramtx, (w,h), 5)
dst = cv.remap(img, mapx, mapy, cv.INTER_LINEAR)
# crop the image
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv.imwrite('calibresult.png', dst)

[링크 : https://docs.opencv.org/4.x/dc/dbb/tutorial_py_calibration.html]

 

Parameters
rvecs Output vector of rotation vectors (Rodrigues ) estimated for each pattern view (e.g. std::vector<cv::Mat>>). That is, each i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter description) brings the calibration pattern from the object coordinate space (in which object points are specified) to the camera coordinate space. In more technical terms, the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space to camera coordinate space. Due to its duality, this tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate space.
tvecs Output vector of translation vectors estimated for each pattern view, see parameter describtion above.
stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters. Order of deviations values: (fx,fy,cx,cy,k1,k2,p1,p2,k3,k4,k5,k6,s1,s2,s3,s4,τx,τy) If one of parameters is not estimated, it's deviation is equals to zero.
stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters. Order of deviations values: (R0,T0,…,RM−1,TM−1) where M is the number of pattern views. Ri,Ti are concatenated 1x3 vectors.
perViewErrors Output vector of the RMS re-projection error estimated for each pattern view.

Returns
the overall RMS re-projection error.

[링크 : https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html#ga3207604e4b1a1758aa66acb6ed5aa65d]

 

+

테스트 이미지를 보정해서 저장하도록 수정

$ cat calib.py 
import cv2
import numpy as np
import os
import glob
# 체커보드의 차원 정의
CHECKERBOARD = (6,9) # 체커보드 행과 열당 내부 코너 수
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# 각 체커보드 이미지에 대한 3D 점 벡터를 저장할 벡터 생성
objpoints = []
# 각 체커보드 이미지에 대한 2D 점 벡터를 저장할 벡터 생성
imgpoints = [] 
# 3D 점의 세계 좌표 정의
objp = np.zeros((1, CHECKERBOARD[0] * CHECKERBOARD[1], 3), np.float32)
objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
prev_img_shape = None
# 주어진 디렉터리에 저장된 개별 이미지의 경로 추출
images = glob.glob('./images/*.jpg')
for fname in images:
    img = cv2.imread(fname)
    # 그레이 스케일로 변환
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    # 체커보드 코너 찾기
    # 이미지에서 원하는 개수의 코너가 발견되면 ret = true
    ret, corners = cv2.findChessboardCorners(gray,
                                             CHECKERBOARD,
                                             cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE)
    # 원하는 개수의 코너가 감지되면,
    # 픽셀 좌표 미세조정 -> 체커보드 이미지 표시
    if ret == True:
        objpoints.append(objp)
        # 주어진 2D 점에 대한 픽셀 좌표 미세조정
        corners2 = cv2.cornerSubPix(gray, corners, (11,11),(-1,-1), criteria)
        imgpoints.append(corners2)
        # 코너 그리기 및 표시
        img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2, ret)
    cv2.imshow('img',img)
    cv2.waitKey(0)
cv2.destroyAllWindows()

h,w = img.shape[:2] # 480, 640
# 알려진 3D 점(objpoints) 값과 감지된 코너의 해당 픽셀 좌표(imgpoints) 전달, 카메라 캘리브레이션 수행
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

images = glob.glob('./images/*.jpg')
for fname in images:
    img = cv2.imread(fname)

    h,  w = img.shape[:2]
    newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))

    dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
    # crop the image
    x, y, w, h = roi
    dst = dst[y:y+h, x:x+w]
    print(fname+'.undisto')
    cv2.imwrite(fname+'.undisto.jpg', dst)

 

2760p 노트북에 달린 웹캠 720p로 해봤는데

먼가 꼼지락 대는거 보면 왜곡이 보정된 것 같기도 하고.. 아닌것 같기도 하고 모르겠다 ㅎㅎ

'Programming > openCV' 카테고리의 다른 글

opencv stereo 계산 알고리즘  (0) 2024.02.24
opencv 스테레오 카메라 깊이 처리하기  (0) 2024.02.21
opencv 카메라 캡쳐 - 최신 이미지 갱신  (0) 2024.01.25
opencv webcam 수동촛점 조절  (0) 2024.01.25
MTM + webcam  (0) 2024.01.16
Posted by 구차니
Programming/openCV2024. 1. 25. 16:03

opencv + python 특징인지 모르겠으나

pc던 arm 보드건 4장 정도 버리고 5번째 받아야 현재 시점의 새로운 이미지가 넘어온다.

VideoCapture.read() 함수는 내부적으로

VideoCapture.grab() 과 VideoCapture.retrieve() 두개를 호출한다는데

grab만 4번 하고 retrieve 안해도 될진 모르겠고(다음에 테스트 해봐야지..)

 

[링크 : https://kali-live.tistory.com/8]

 

cv2.waitKey() 하면 혹시나 내부 쓰레드가 돌아갈까 싶어서 했는데 이것도 아니긴 하다.

Try placing cv::waitKey(0); before cap0.read(frame0); instead of after: if (!frame0.empty()) cv::waitKey(0);. The issue is, that you are not going to see the video. If you want to watch the video, and pause when key is pressed, replace cv::waitKey(0); with: int key = cv::waitKey(1);if (key > 0) cv::waitKey(0); 
– Rotem
 Oct 21, 2022 at 9:09

[링크 : https://stackoverflow.com/questions/74145112/how-can-i-get-the-most-current-frame-in-opencv]]

Posted by 구차니
Programming/openCV2024. 1. 25. 09:54

 

로지텍 C920 사용하는데 얘는 자동 촛점이 되는 녀석이다.

그래서 영상에 따라서는 가끔 이상한(?) 먼 곳에 촛점이 잡히는 경우가 있는데

수동으로 촛점을 조절하거나, 고정하는 방법을 찾는 중

 

guvcview 에서는 아래와 같이 Focus, Automatic Continous를 끄고

Focus. Absolute에서 설정을 해주면 된다. 0~255 범위

그래서 적당히 먼곳(중앙의 금속)은 60

 

좀 더 가까운 알루미늄 빛의 금속은 124. 숫자가 클수록 더 가까워진다.

 

촛점 값은 CAP_PROP_FOCUS 으로 설정하는데

CAP_PROP_FOCUS 
Python: cv.CAP_PROP_FOCUS
cv::CAP_PROP_FOCUS =28,

[링크 : https://docs.opencv.org/3.4/d4/d15/group__videoio__flags__base.html#ggaeb8dd9c89c10a5c63c139bf7c4f5704da25fe3d87b62a918427d49f3d43aef714]

 

focus를 수동으로 설정하기 위해서는 일단 autofocus를 끄고(0으로 설정) 해주어야 한다.

CAP_PROP_AUTOFOCUS 
Python: cv.CAP_PROP_AUTOFOCUS
cv::CAP_PROP_AUTOFOCUS =39,

[링크 : https://docs.opencv.org/3.4/d4/d15/group__videoio__flags__base.html#ggaeb8dd9c89c10a5c63c139bf7c4f5704dad937a854bd8d1ca73edfb3570e799aa3]

 

[링크 : https://docs.opencv.org/3.4/d4/d15/group__videoio__flags__base.html]

[링크 : https://stackoverflow.com/questions/19813276/manually-focus-webcam-from-opencv#comment122198940_42819965]

Posted by 구차니
Programming/openCV2024. 1. 16. 11:34

MTM + webcam

pc에서는 잘도는데 arm에서 잘되려나..

 

import MTM, cv2
import numpy as np

letter_a = cv2.imread('letter_a.png', 0)
letter_b = cv2.imread('letter_b.png', 0)
letter_c = cv2.imread('letter_c.png', 0)
letter_d = cv2.imread('letter_d.png', 0)

letter_a.astype(np.uint8)
letter_b.astype(np.uint8)
letter_c.astype(np.uint8)
letter_d.astype(np.uint8)

listTemplates = [('A', letter_a),
                 ('B', letter_b),
                 ('C', letter_c),
                 ('D', letter_d)]

webcam = cv2.VideoCapture(2)
webcam.set(cv2.CAP_PROP_FRAME_WIDTH, 1024)
webcam.set(cv2.CAP_PROP_FRAME_HEIGHT, 768)

def drawBoxesOnRGB2(image, tableHit, boxThickness=2, boxColor=(255, 255, 00), showLabel=False, labelColor=(255, 255, 0), labelScale=0.5 ):
    # Convert Grayscale to RGB to be able to see the color bboxes
    if image.ndim == 2: outImage = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) # convert to RGB to be able to show detections as color box on grayscale image
    else:               outImage = image.copy()

    for _, row in tableHit.iterrows():
        x,y,w,h = row['BBox']
        score = row['Score']
        cv2.rectangle(outImage, (x, y), (x+w, y+h), color=boxColor, thickness=boxThickness)
        if showLabel: cv2.putText(outImage, text=row['TemplateName'] + "@" + str(score * 100), org=(x, y), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=labelScale, color=labelColor, lineType=cv2.LINE_AA)

    return outImage

if not webcam.isOpened():
    print("Could not open webcam")
    exit()

while webcam.isOpened():
    status, image = webcam.read()
    image.astype(np.uint8)
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    tableHit = MTM.matchTemplates(listTemplates, image_gray, score_threshold=0.8, method=cv2.TM_CCOEFF_NORMED, maxOverlap=0)
    print("Found {} letters".format(len(tableHit)))
    print(tableHit)

    Overlay = drawBoxesOnRGB2(image, tableHit, showLabel=True)

    if status:
        cv2.imshow("test", Overlay)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

webcam.release()
cv2.destroyAllWindows()

[링크 : https://medium.com/quantrium-tech/object-detection-multi-template-matching-2c9c9fc1a867]

[링크 : https://github.com/multi-template-matching/MultiTemplateMatching-Python]

 

열고 해상도 바꾸는게 안되면, 열면서 해상도 설정하면 됨.

cap = cv2.VideoCapture(1, apiPreference=cv2.CAP_ANY, params=[
    cv2.CAP_PROP_FRAME_WIDTH, 1280,
    cv2.CAP_PROP_FRAME_HEIGHT, 1024])

[링크 : https://stackoverflow.com/questions/71310212/python-cv2-videocapture-has-wrong-resolution-and-read-cropped-images]

'Programming > openCV' 카테고리의 다른 글

opencv 카메라 캡쳐 - 최신 이미지 갱신  (0) 2024.01.25
opencv webcam 수동촛점 조절  (0) 2024.01.25
opencv cv2.imshow() error  (0) 2024.01.16
opencv를 이용한 다중 템플릿 추적  (0) 2024.01.15
cv2.imshow cv2.waitKey  (0) 2022.03.14
Posted by 구차니
Programming/openCV2024. 1. 16. 10:54

잘되더니 버전이 올라가서 그런가 배를 짼다.

실행 환경은 i.mx8mp evk / wayland 환경이라 그런가..

그런데 잘되다가 pip로 이것저것 x86도 갈아 엎었더니 똑같이 문제가 발생..

 

에러는 아래와 같은데 어떤 패키지를 설치하라고 한다. libgtk 라.. wayland 되면서 들어내버린건가?

Traceback (most recent call last):
  File "/home/falinux/work/src/cv2/cam2.py", line 31, in <module>
    cv2.imshow("test", image)
cv2.error: OpenCV(4.9.0) /io/opencv/modules/highgui/src/window.cpp:1272: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage'

 

아무튼 패키지 깔고, pip로 깔아주니 해결

sudo apt install libgtk2.0-dev pkg-config
pip install opencv-contrib-python

[링크 : https://stackoverflow.com/questions/42843316/how-to-include-libgtk2-0-dev-and-pkg-config-in-cmake-when-installing-opencv-on-u]

 

디자인이 먼가 바뀌었다?

'Programming > openCV' 카테고리의 다른 글

opencv webcam 수동촛점 조절  (0) 2024.01.25
MTM + webcam  (0) 2024.01.16
opencv를 이용한 다중 템플릿 추적  (0) 2024.01.15
cv2.imshow cv2.waitKey  (0) 2022.03.14
virtual mouse  (0) 2022.01.25
Posted by 구차니
Programming/openCV2024. 1. 15. 10:48

 

일반적인 템플릿 매칭은 가장 매칭되는 하나의 녀석만 찾는데

트럼프 카드와 같이 여러개의 도형이 있을 경우 여러개를 다 찾는 방법을 제공함.

[링크 : https://pyimagesearch.com/2021/03/29/multi-template-matching-with-opencv/]

 

yolo 외에도 쓸 수 있는 방법이었나?

[링크 : https://pyimagesearch.com/2014/11/17/non-maximum-suppression-object-detection-python/]

 

openCV 문서에서도 발견

minMaxLoc을 안쓰면 되다고. (응?)

    res = cv.matchTemplate(img,template,method)
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    cv.rectangle(img,top_left, bottom_right, 255, 2)
res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)
for pt in zip(*loc[::-1]):
    cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)

[링크 : https://docs.opencv.org/3.4/d4/dc6/tutorial_py_template_matching.html]

 

아래 그림 하나로 설명.

원래 내가 원하던 건데.. x86이 아닌 arm에서도 되려나?

[링크 : https://medium.com/quantrium-tech/object-detection-multi-template-matching-2c9c9fc1a867]

[링크 : https://pypi.org/project/Multi-Template-Matching/]

'Programming > openCV' 카테고리의 다른 글

MTM + webcam  (0) 2024.01.16
opencv cv2.imshow() error  (0) 2024.01.16
cv2.imshow cv2.waitKey  (0) 2022.03.14
virtual mouse  (0) 2022.01.25
opencv-3.4.0 어플리케이션 빌드  (0) 2021.01.14
Posted by 구차니