如何从此图像中去除正确的噪声?
How to remove a right noise from this image?
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)
cv2.imshow('thresh', 阈值)
我假设您只希望拥有图像的中间部分并从图像中删除其他所有内容。一种简单的方法是搜索轮廓,select 最大轮廓的边界框并将其绘制在新创建的蒙版上。
示例代码:
import cv2
import numpy as np
img = cv2.imread("1.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY_INV)[1]
contours = cv2.findContours(thresh, cv2.CHAIN_APPROX_NONE, cv2.RETR_TREE)[0]
cnt = max(contours, key=lambda c: cv2.contourArea(c))
mask = np.ones((img.shape[:2]), np.uint8)*255
x, y, w, h = cv2.boundingRect(cnt)
mask[y:y+h, x:x+w] = gray[y:y+h, x:x+w]
cv2.imwrite("mask.png", mask)
cv2.imshow("mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
编辑:
这就是我尝试根据您输入的图像制作它的方式
import cv2
import numpy as np
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
contours = cv2.findContours(thresh, cv2.CHAIN_APPROX_NONE, cv2.RETR_TREE)[0]
cnt = max(contours, key=lambda c: cv2.contourArea(c))
mask = np.ones((img.shape[:2]), np.uint8)*255
mask2 = np.zeros((img.shape[:2]), dtype=np.uint8)
cv2.drawContours(mask, [cnt], -1, (0, 0, 0), -1)
x, y, w, h = cv2.boundingRect(cnt)
mask2[y:y+h, x:x+w] = gray[y:y+h, x:x+w]
cv2.imshow('mask2', mask2)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
close = 255 - cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)
cv2.imshow('thresh', 阈值)
我假设您只希望拥有图像的中间部分并从图像中删除其他所有内容。一种简单的方法是搜索轮廓,select 最大轮廓的边界框并将其绘制在新创建的蒙版上。
示例代码:
import cv2
import numpy as np
img = cv2.imread("1.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY_INV)[1]
contours = cv2.findContours(thresh, cv2.CHAIN_APPROX_NONE, cv2.RETR_TREE)[0]
cnt = max(contours, key=lambda c: cv2.contourArea(c))
mask = np.ones((img.shape[:2]), np.uint8)*255
x, y, w, h = cv2.boundingRect(cnt)
mask[y:y+h, x:x+w] = gray[y:y+h, x:x+w]
cv2.imwrite("mask.png", mask)
cv2.imshow("mask", mask)
cv2.waitKey(0)
cv2.destroyAllWindows()
编辑:
这就是我尝试根据您输入的图像制作它的方式
import cv2
import numpy as np
img = cv2.imread('1.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
thresh = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
contours = cv2.findContours(thresh, cv2.CHAIN_APPROX_NONE, cv2.RETR_TREE)[0]
cnt = max(contours, key=lambda c: cv2.contourArea(c))
mask = np.ones((img.shape[:2]), np.uint8)*255
mask2 = np.zeros((img.shape[:2]), dtype=np.uint8)
cv2.drawContours(mask, [cnt], -1, (0, 0, 0), -1)
x, y, w, h = cv2.boundingRect(cnt)
mask2[y:y+h, x:x+w] = gray[y:y+h, x:x+w]
cv2.imshow('mask2', mask2)
cv2.imshow('mask', mask)
cv2.waitKey(0)
cv2.destroyAllWindows()