数字图像的概念与性质
import numpy as np
def distanceTransform(img):
# 默认传入参数为二值图,子集为0,其余为无穷大(255)
result = img.copy()
rows, cols = result.shape
AL = np.array([[-1, 0], [-1, -1], [0, -1], [1, -1]])
BR = np.array([[1, 0], [1, 1], [0, 1], [-1, 1]])
for col in range(cols):
for row in range(rows):
for next in AL:
[next_row, next_col] = [row, col] + next
if 0 <= next_row < rows and 0 <= next_col < cols:
if result[next_row, next_col]+abs(row-next_row)+abs(col-next_col) < result[row, col]:
result[row, col] = result[next_row, next_col]+abs(row-next_row)+abs(col-next_col)
for col in range(cols-1, -1, -1):
for row in range(rows-1, -1, -1):
for next in BR:
[next_row, next_col] = [row, col] + next
if 0 <= next_row < rows and 0 <= next_col < cols:
if result[next_row, next_col]+abs(row-next_row)+abs(col-next_col) < result[row, col]:
result[row, col] = result[next_row, next_col]+abs(row-next_row)+abs(col-next_col)
return result
边缘与边界
边缘:像素与其直接邻接的局部性质,是图像上亮度的不连续点,是矢量。方向与梯度垂直,大小与梯度相等。
边界是与区域有关的全局概念
噪声
加性噪声:噪声与图像信号无关
乘性噪声:噪声幅值与信号本身幅值有关
def hist_equal(img):
rows, cols = img.shape
S = rows * cols * 1.0
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
cum_hist = np.cumsum(hist)
T = np.zeros(256)
out = np.zeros_like(img)
for i in range(256):
T[i] = np.round(255.0/S * cum_hist[i])
for row in range(rows):
for col in range(cols):
out[row, col] = T[img[row, col]]
out = cv2.convertScaleAbs(out)
return out
def Robert_detection(img, threshold=-1):
kernel1 = np.array([[-1, 0], [0, 1]])
kernel2 = np.array([[0, -1], [1, 0]])
img1 = cv2.filter2D(img, cv2.CV_32F, kernel1) # 获取-45°方向的偏导
img2 = cv2.filter2D(img, cv2.CV_32F, kernel2) # 获取-135°方向的偏导
mag = cv2.magnitude(img1, img2)
mag = cv2.convertScaleAbs(mag)
if threshold == -1: # 如果没有给定阈值则通过Otsu二值化
_, mag = cv2.threshold(mag, 0, 255, cv2.THRESH_OTSU)
else:
mag[mag >= threshold] = 255
mag[mag < threshold] = 0
return mag
def Sobel_detection(img, threshold=-1):
dx = cv2.Sobel(img, cv2.CV_32F, 1, 0) # 获取水平方向的偏导
dy = cv2.Sobel(img, cv2.CV_32F, 0, 1) # 获取竖直方向的偏导
mag = cv2.magnitude(dx, dy)
mag = cv2.convertScaleAbs(mag)
if threshold == -1:
_, mag = cv2.threshold(mag, 0, 255, cv2.THRESH_OTSU)
else:
mag[mag >= threshold] = 255
mag[mag < threshold] = 0
return mag
def Prewitt_detection(img, threshold=-1):
kernel1 = np.array([[-1, -1, -1], [0, 0, 0], [1, 1, 1]])
kernel2 = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
dx = cv2.filter2D(img, cv2.CV_32F, kernel2)
dy = cv2.filter2D(img, cv2.CV_32F, kernel1)
mag = cv2.magnitude(dx, dy)
mag = cv2.convertScaleAbs(mag)
if threshold == -1:
_, mag = cv2.threshold(mag, 0, 255, cv2.THRESH_OTSU)
else:
mag[mag >= threshold] = 255
mag[mag < threshold] = 0
return mag
def Laplacian_detection(img, threshold=-1):
out = cv2.Laplacian(img, cv2.CV_32F, ksize=3)
out = cv2.convertScaleAbs(out)
if threshold == -1:
_, out = cv2.threshold(out, 0, 255, cv2.THRESH_OTSU)
else:
out[out >= threshold] = 255
out[out < threshold] = 0
return out
版权所有:江苏和讯自动化设备有限公司所有 备案号:苏ICP备2022010314号-1
技术支持: 易动力网络