这个代码有什么问题import cv2 import numpy as np img = cv2.imread(r'E:\\postgraduate\\three\\DIP3E_Original_Images_CH03\\1.tif',0) def invert_image(img): height, width = img.shape Image = np.zeros((height,width), np.uint8) for i in range(0, height): for j in range(0, width): imgPixel = img[i, j] Image[i, j] = 255-imgPixel return Image cv2.namedWindow('Image1') cv2.imshow('Image1', Image) cv2.waitKey(0) cv2.destoryAllWindows()
时间: 2024-02-14 10:05:39 浏览: 60
这段代码存在几个问题:
1. `cv2.destoryAllWindows()` 应该是 `cv2.destroyAllWindows()`,拼写错误。
2. 函数 `invert_image` 没有正确缩进,导致 `return` 语句在第一次循环时就被执行了,因此只会处理第一行像素,并返回结果。
3. 函数最后的 `cv2.namedWindow('Image1')`, `cv2.imshow('Image1', Image)` 和 `cv2.waitKey(0)` 应该在函数外部调用,否则函数执行完后窗口会立即关闭。
下面是修正后的代码:
```python
import cv2
import numpy as np
img = cv2.imread(r'E:\\postgraduate\\three\\DIP3E_Original_Images_CH03\\1.tif', 0)
def invert_image(img):
height, width = img.shape
Image = np.zeros((height, width), np.uint8)
for i in range(0, height):
for j in range(0, width):
imgPixel = img[i, j]
Image[i, j] = 255 - imgPixel
return Image
Image = invert_image(img)
cv2.namedWindow('Image1')
cv2.imshow('Image1', Image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文