opencv 裁剪图像和关键点

klr1opcd  于 2022-12-13  发布在  其他
关注(0)|答案(1)|浏览(139)

我想裁剪一个边缘平滑的图像(最好使用轮廓),并在中间得到关键点。任何帮助都非常感谢。
原始图像:

我试过下面的代码

import cv2 as cv
import numpy as np

img_ref = cv.imread('img.jpeg')
img1 = cv.cvtColor(img_ref, cv.COLOR_BGR2GRAY)
img1_blur = cv.GaussianBlur(img1, (7, 7), cv.BORDER_DEFAULT)

# create mask
thresh, img1_edges1 = cv.threshold(img1_blur, 100, 255, cv.THRESH_BINARY_INV)

# remove noise
img1_edges2 = cv.dilate(img1_edges1, (3, 3), iterations=1)
img1_edges3 = cv.morphologyEx(img1_edges2, cv.MORPH_CLOSE, (7, 7))
mask_img = cv.morphologyEx(img1_edges3, cv.MORPH_OPEN, (7, 7))

# mask the original image
img1_masked = cv.bitwise_and(img_ref, img_ref, mask=mask_img)

# initiate ORB and find the keypoints with SIFT
orb = cv.ORB_create(200)
kp1, des1 = orb.detectAndCompute(img1_masked, None)

img1kp = cv.drawKeypoints(img1_masked, kp1, None, flags=None)

cv.imshow('mask', mask_img)
cv.imshow('key_point', img1kp)
cv.waitKey(0)

遮罩结果(不干净,边缘不平滑):

我已经使用轮廓的面具,但它没有工作。
关键点(所有边缘周围):

先谢了

guicsvcw

guicsvcw1#

对于裁剪,这种方法已经工作与我的一些图像

import cv2
import numpy as np
import skimage.exposure

# load image
img_ref = cv2.imread('wing_image.tif')

# convert to gray
gray = cv2.cvtColor(img_ref, cv2.COLOR_BGR2GRAY)

# threshold
img_thresh = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)[1]

# blur threshold image
img_blur = cv2.GaussianBlur(img_thresh, (0,0), sigmaX=3, sigmaY=3, borderType = cv2.BORDER_DEFAULT)

# stretch so that 255 -> 255 and 127.5 -> 0
img_stretch = skimage.exposure.rescale_intensity(img_blur, in_range=(127.5,255), out_range=(0,255)).astype(np.uint8)

# threshold again
img_thresh2 = cv2.threshold(img_stretch, 100, 255, cv2.THRESH_BINARY)[1]

# get external contour
cnts = cv2.findContours(img_thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

maxcontour = max(cnts, key=cv2.contourArea, default=0)

# draw white filled contour on black background

contour = np.zeros_like(img_thresh2, dtype=np.uint8)
contour.fill(0)
mask1 = cv2.drawContours(contour, [maxcontour], 0, 255, -1)

# dilate mask for dark border
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20,20))
mask2 = cv2.morphologyEx(mask1, cv2.MORPH_DILATE, kernel)

# apply mask to img
mask3 = cv2.bitwise_not(mask2)
img_masked = cv2.bitwise_and(img_ref, img_ref, mask=mask3)

和获取关键点(不是边缘周围)已经解决了。我非常感谢你的帮助

相关问题