Python np数组无法读取我的负值

2024-09-30 20:37:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从事一个项目,该项目应做到以下几点: 制作一个Python程序,可以在图像中找到对角边。 输入:灰度图像 输出:对角线边缘为白色(255)和其余像素的二值图像 黑色(0)”

这是original picture

这是我的current output

这不是我想要的,我想我找到了问题所在。我的np.数组(SobelKernel)与pixelValue相乘时不使用负值(通过打印进行检查)。你知道怎么解决吗?你知道吗

这是我的密码:

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


img = cv2.imread('LENNA.JPG')
height = img.shape[1]  
width = img.shape[0] 

out = np.zeros(img.shape, np.uint8)

SobelKernel = np.array([[2, 1, 0],
                        [1, 0, -1],
                        [0, -1, -2]], np.int8)    

for y in range(1, height-1): 
    for x in range(1, width-1): 
        temp = 0

        for j in range(2): 
            for k in range(2):
                pixValue = img[x+ j - 1][y + k - 1]
                kernelValue = SobelKernel[j][k]
                temp = temp + pixValue*kernelValue
                #print(Sobelkernel[j][k])
        out[x, y] = temp 

cv2.imshow('test', out)
cv2.waitKey(0)
cv2.destroyAllWindows()

Tags: 项目in图像importimgforasnp
1条回答
网友
1楼 · 发布于 2024-09-30 20:37:53

问题是生成的图像可能超出int8的边界。你知道吗

将结果保存在out = np.zeros(img.shape, np.int16)中,然后处理低于0或高于255的值。你知道吗

然后在处理超出范围的值之后,在保存之前将数组强制转换回np.unit8(否则,它将被视为16位图像,而不是8位图像)。你知道吗

相关问题 更多 >