python专题python干货

opencv-python梯度特征提取的意外收获-彩色图的阈值分

2020-10-12  本文已影响0人  1037号森林里一段干木头

在一个项目中需要提取图像的梯度特征,用的sobel算子提取图像的梯度(因为sobel天生具有加权平均抑制噪声的特点,所以拿它来提取梯度特征)。sobel算子有x,y方向,分别提取图像横向纵向的梯度,最后加权融合为整图的梯度。原本是想在梯度图中筛掉那些不是很强的梯度,但是代码中写成在原图中筛选,得到了另外一种结果,看起来挺漂亮的hahaha(果然人是视觉动物.....)。

th=max_value*0.5#梯度强的地方说明边缘特征明显,可以做参考
res,grad=cv2.threshold(img,th,255,cv2.THRESH_BINARY)

先上结果


1.PNG 2.PNG 3.PNG

全部代码如下:


import cv2
import numpy as np
import matplotlib.pyplot as plt
import os

img_folder_path=r"F:\imagedata\other"

def grad_x(img):
    grad_x = cv2.Sobel(img, cv2.CV_16S, 1, 0, ksize=3)
    grad_x = cv2.convertScaleAbs(grad_x)
    return grad_x

def grad_y(img):
    grad_y = cv2.Sobel(img, cv2.CV_16S, 0, 1, ksize=3)
    grad_y = cv2.convertScaleAbs(grad_y)
    return grad_y
   
def grad_xy(grad_x,grad_y):
    return cv2.addWeighted(grad_x, 0.5, grad_y, 0.5, 0)

def select(grad):
    max_value=np.max(grad)
    th=max_value*0.5#梯度强的地方说明边缘特征明显,可以做参考
    res,grad=cv2.threshold(img,th,255,cv2.THRESH_BINARY)
    return grad

window_name = ('src') 
cv2.namedWindow(window_name,cv2.WINDOW_FREERATIO)
window_name_b = ('grad_x') 
cv2.namedWindow(window_name_b,cv2.WINDOW_FREERATIO)
window_name_g = ('grad_y') 
cv2.namedWindow(window_name_g,cv2.WINDOW_FREERATIO)
window_name_r = ('grad_xy') 
cv2.namedWindow(window_name_r,cv2.WINDOW_FREERATIO)

i=0
for item in os.listdir(img_folder_path):
    i+=1
    if i<10 or i>40:
        continue
    item_path=os.path.join(img_folder_path,item)
    if os.path.isdir(item_path):
        print(item_path)
        continue
    else:
        img=cv2.imread(item_path)
        img = cv2.GaussianBlur(img,(15,15),0)
        #img = cv2.medianBlur(img,9)#中值
        #img=cv2.blur(img,(5,5)) #均值滤波
        cv2.imshow(window_name,img)
        
        img_gx=grad_x(img[:,:,2])
        cv2.imshow(window_name_b,img_gx)
        img_gy=grad_y(img[:,:,2])
        cv2.imshow(window_name_g,img_gy)
        img_xy=grad_xy(img_gx,img_gy)
        cv2.imshow(window_name_r,img_xy)
        cv2.waitKey(0)
        #_,img_xy= cv2.threshold(img[:,:,2],0,125,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
        img_xy=select(img_xy)
        cv2.imshow(window_name_r,img_xy)
        cv2.waitKey(0)

cv2.destroyAllWindows() 
上一篇下一篇

猜你喜欢

热点阅读