import cv2
import random
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
maskpath = './12.jpg'
imagepath = './Image/12.jpg'
img = cv2.imread(imagepath)
mask = cv2.imread(maskpath)
h_w = img.shape
height = h_w[0]
weight = h_w[1]
gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
gray_mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)
# imgG = cv2.GaussianBlur(gray_img, (3, 3), 5)
imgG = cv2.medianBlur(gray_img, 5)
cv2.imshow('imgG', imgG)
empty_img = np.zeros((height, weight, 3), np.uint8)
# print(empty_img)
ret, thresh = cv2.threshold(gray_mask, 127, 255, 0)
_, contours, hierarchy = cv2.findContours(thresh, 2, 1)
# Gx = np.array([[-1, 0, 0, 0, 1],
# [0, 0, 0, 0, 0],
# [-2, 0, 0, 0, 2],
# [0, 0, 0, 0, 0],
# [-1, 0, 0, 0, 1]])
Gx = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
Gy = np.transpose(Gx)
# print(Gy)
def cpt_grad(dst_mat):
# dst_mat = np.empty((3,3))
gx = signal.convolve(dst_mat,Gx, mode='valid')
gy = signal.convolve(dst_mat,Gy, mode='valid')
all_grad = math.sqrt(gx*gx + gy*gy)
return all_grad
# print(len(contours))
# print(contours)
# cv2.imshow('imgG',mask)
# plt.imshow(mask)
for cnt in contours:
for pix in cnt:
# print(pix)
for i in pix:
length = len(i)
# print(i[0],i[1])
# img_mat = np.array([[imgG[i[0]-2,i[1]-2], 0, imgG[i[0],i[1]-2], 0, imgG[i[0]+2,i[1]-2]],
# [0, 0, 0, 0, 0],
# [imgG[i[0]-2,i[1]], 0, imgG[i[0],i[1]], 0, imgG[i[0]+2,i[1]]],
# [0, 0, 0, 0, 0],
# [imgG[i[0]-2,i[1]+2], 0, imgG[i[0],i[1]+2], 0, imgG[i[0]+2,i[1]+2]]])
img_mat = np.array([[imgG[i[0] - 1, i[1] + 1], imgG[i[0], i[1] + 1], imgG[i[0] + 1, i[1] + 1]],
[imgG[i[0] - 1, i[1]], imgG[i[0], i[1]], imgG[i[0] + 1, i[1]]],
[imgG[i[0] - 1, i[1] - 1], imgG[i[0], i[1] - 1], imgG[i[0] + 1, i[1] - 1]]])
print(img_mat)
# print(img_mat)
pix_grad = cpt_grad(img_mat)
# print('这是我们计算的梯度:',pix_grad)
# gy = imgG[i[0],i[1]]*1 + imgG[i[0],i[1]+1]*2 + imgG[i[0],i[1]+2]*1-imgG[i[0]+2,i[1]]*1-imgG[i[0+2]]
# print(i)
# print(cnt)
# cv2.line(mask, tuple(i), tuple(i + 1), (255, 255, 255), 2)
cv2.line(empty_img, tuple(i), tuple(i + 1), (255, 0, 0), 1)
if pix_grad < 20:
print('grad小于20的像素点坐标:',(i[0], i[1]))
empty_img[i[1], i[0]] = (0, 0, 255)
# empty_img[i[1], i[0]-1] = (0, 0, 255)
# empty_img[i[1], i[0]+1] = (0, 0, 255)
cv2.imwrite('./grad_img1.jpg', empty_img)
cv2.imshow('contours', empty_img)
cv2.waitKey()
使用第二幅图的边缘信息,计算第一幅图对应位置的梯度信息,我也做了一些尝试,我将梯度小于20的像素标为红色,但是效果并不理想。结果如下图。
我主要使用了sobel算子作为计算梯度的工具,将x,y方向计算的值相加。
我想根据第二幅图的边缘点的位置信息获取第一幅图对应位置的梯度值,也就是求第一幅图的边缘梯度。所求梯度在正常的边缘上应该具有明显梯度值,而在红色圆圈处计算的梯度是较小的。
你这第二张图和第一张图根本就不是同一个图像出来的,你确定第二张图的边缘信息和第一张图能对的上?点都对应不了你这么求没啥意义。
不然你就以第二张图为mask,将轮廓外的置为255,然后贴到第一张图上面去做mask,你看下剩下结果是不是都是边缘