此代码问题import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread(r'E:\\postgraduate\\three\\DIP3E_Original_Images_CH03\\3.14.tif',0) def bit_plane_slicing(src,z,n): height, width= src.shape dst = np.zeros((height, width), np.uint8) for i in range(0, height): for j in range(0, width): pixel = format(src[i,j], '08b') if pixel[8-z] == '0': dst[i, j] = 0 else: dst[i, j] = 255 dst = np.bitwise_and(dst, n) return dst image1 = bit_plane_slicing(img,8,7) image2 = bit_plane_slicing(image1,8,6) image3 = bit_plane_slicing(image2,8,5) plt.figure(figsize=(100,100)) plt.subplot(131) plt.imshow(image1,cmap='gray') plt.axis('off') plt.subplot(132) plt.imshow(image2,cmap='gray') plt.axis('off') plt.subplot(133) plt.imshow(image3,cmap='gray') plt.axis('off') plt.show()
时间: 2024-02-14 13:13:05 浏览: 85
这段代码的问题是:在 `bit_plane_slicing` 函数中,`dst = np.bitwise_and(dst, n)` 的位置不正确,应该放在第二个 `for` 循环的外面。另外,建议在 `imshow` 函数中添加 `vmin=0, vmax=255` 参数。
修改后的代码如下:
```
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread(r'E:\\postgraduate\\three\\DIP3E_Original_Images_CH03\\3.14.tif',0)
def bit_plane_slicing(src,z,n):
height, width = src.shape
dst = np.zeros((height, width), np.uint8)
for i in range(0, height):
for j in range(0, width):
pixel = format(src[i,j], '08b')
if pixel[8-z] == '0':
dst[i, j] = 0
else:
dst[i, j] = 255
dst = np.bitwise_and(dst, n)
return dst
image1 = bit_plane_slicing(img,8,7)
image2 = bit_plane_slicing(image1,8,6)
image3 = bit_plane_slicing(image2,8,5)
plt.figure(figsize=(100,100))
plt.subplot(131)
plt.imshow(image1,cmap='gray', vmin=0, vmax=255)
plt.axis('off')
plt.subplot(132)
plt.imshow(image2,cmap='gray', vmin=0, vmax=255)
plt.axis('off')
plt.subplot(133)
plt.imshow(image3,cmap='gray', vmin=0, vmax=255)
plt.axis('off')
plt.show()
```
这样修改后,就可以正确地显示三个子图了。
阅读全文