数字图像处理(基于逻辑运算的边缘检测)

学习中......

1.绘制原图像的直方图

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

ricea=cv.imread("./lenargb1.jpg")
# print(ricea)
width=ricea.shape[1]
height=ricea.shape[0]
hist1=cv.calcHist([ricea],[0],None,[256],[0,256])
plt.title("Histogram");plt.plot(hist1, color="g")#曲线直方图

结果图1数字图像处理(基于逻辑运算的边缘检测)_第1张图片

2. 根据直方图,选择合适的阈值进行二值化处理得到二值化图像

new_img = cv.cvtColor(ricea, cv.COLOR_BGR2GRAY)
height, width = new_img.shape[0:2]

# 设置阈值
thresh = 80

# 遍历每一个像素点
for row in range(height):
    for col in range(width):
        # 获取到灰度值
        gray = new_img[row, col]
        # 如果灰度值高于阈值 就等于255最大值
        if gray > thresh:
            new_img[row, col] = 255
        # 如果小于阈值,就直接改为0
        elif gray < thresh:
            new_img[row, col] = 0

cv.imshow('image', new_img)
cv.waitKey()

数字图像处理(基于逻辑运算的边缘检测)_第2张图片

 

3.使用逻辑运算得到图像的边缘图像

gaussianBlur = cv.GaussianBlur(ricea, (3,3), 0)
ret, binary = cv.threshold(gaussianBlur, 75, 255, cv.THRESH_BINARY)
affine_arrl = np.float32([[1,0,-1],[0,1,0]])#左移一个像素
ricelb= cv.warpAffine(binary,affine_arrl,(width,height))
ricelc=cv.bitwise_or(binary,ricelb)
riceld=cv.bitwise_xor(binary,ricelc)
affine_arrr = np.float32([[1,0,1],[0,1,0]])#右移一个像素
ricerb= cv.warpAffine(binary,affine_arrr,(width,height))
ricerc=cv.bitwise_or(binary,ricerb)
ricerd=cv.bitwise_xor(binary,ricerc)
affine_arru = np.float32([[1,0,0],[0,1,-1]])#上移一个像素
riceub= cv.warpAffine(binary,affine_arru,(width,height))
riceuc=cv.bitwise_or(binary,riceub)
riceud=cv.bitwise_xor(binary,riceuc)
affine_arrd = np.float32([[1,0,0],[0,1,1]])#下移一个像素
ricedb= cv.warpAffine(binary,affine_arrd,(width,height))
ricedc=cv.bitwise_or(binary,ricedb)
ricedd=cv.bitwise_xor(binary,ricedc)
#或运算得到边缘
riceedges1=cv.bitwise_or(riceld,ricerd)
riceedges2=cv.bitwise_or(riceud,ricedd)
riceedges=cv.bitwise_or(riceedges1,riceedges2)
riceedgesrgb=riceedges[:,:,::-1]
plt.figure()
plt.imshow(riceedgesrgb)
plt.title("riceedgesrgb")

数字图像处理(基于逻辑运算的边缘检测)_第3张图片

 

你可能感兴趣的:(计算机视觉,人工智能,python)