Python 如何改进边缘检测并从图像中去除背景?
我正在使用下面的代码删除图像的背景并仅突出显示我的感兴趣区域(ROI),但是,该算法在某些图像中的行为是错误的,丢弃污点(ROI)并与背景一起删除Python 如何改进边缘检测并从图像中去除背景?,python,image,opencv,image-processing,opencv3.0,Python,Image,Opencv,Image Processing,Opencv3.0,我正在使用下面的代码删除图像的背景并仅突出显示我的感兴趣区域(ROI),但是,该算法在某些图像中的行为是错误的,丢弃污点(ROI)并与背景一起删除 import numpy as np import cv2 #Read the image and perform threshold img = cv2.imread('photo.bmp') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray,5) _,
import numpy as np
import cv2
#Read the image and perform threshold
img = cv2.imread('photo.bmp')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.medianBlur(gray,5)
_,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
#Search for contours and select the biggest one
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
cnt = max(contours, key=cv2.contourArea)
#Create a new mask for the result image
h, w = img.shape[:2]
mask = np.zeros((h, w), np.uint8)
#Draw the contour on the new mask and perform the bitwise operation
cv2.drawContours(mask, [cnt],-1, 255, -1)
res = cv2.bitwise_and(img, img, mask=mask)
#Display the result
cv2.imwrite('photo.png', res)
#cv2.imshow('img', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
我不知道我是否理解正确,因为当我运行你的代码时,我没有得到你发布的输出(退出)。如果你只想得到鼹鼠,那就不能通过简单的阈值化来实现,因为鼹鼠离边界太近了,再加上如果你看你的图像,克洛斯利,你会发现它有某种帧。但是,有一种简单的方法可以对该图像执行此操作,但在其他情况下可能不起作用。你可以在你的图像上画一个假边界,把ROI和其他噪声区域分开。然后为要显示的轮廓设置一个阈值。干杯 例如:
#Import all necessery libraries
import numpy as np
import cv2
#Read the image and perform threshold and get its height and weight
img = cv2.imread('moles.png')
h, w = img.shape[:2]
# Transform to gray colorspace and blur the image.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
# Make a fake rectangle arround the image that will seperate the main contour.
cv2.rectangle(blur, (0,0), (w,h), (255,255,255), 10)
# Perform Otsu threshold.
_,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
# Create a mask for bitwise operation
mask = np.zeros((h, w), np.uint8)
# Search for contours and iterate over contours. Make threshold for size to
# eliminate others.
_, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
for i in contours:
cnt = cv2.contourArea(i)
if 1000000 >cnt > 100000:
cv2.drawContours(mask, [i],-1, 255, -1)
# Perform the bitwise operation.
res = cv2.bitwise_and(img, img, mask=mask)
# Display the result.
cv2.imwrite('mole_res.jpg', res)
cv2.imshow('img', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
我明白了,它起作用了。只有ROI未到达边缘的图像不会返回着色,如何使该算法既适用于到达边缘的图像,又适用于未到达边缘的图像?不能从我的头顶说。你试过其他图片吗?如果失败了,你应该提出一个新问题,并给出一些代码失败的例子。