利用Python和OpenCV将图像灰度图转为3D图并显示
写文章的时候为了比较不同滤波器对灰度图像的滤波效果,需要将灰度图进行3D可视化,在网上搜索了很久,只搜到了matlab版本的,没有见到Python相关资源,然后就写了一下,和大家分享一下
import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dif __name__ == "__main__":img_path = r"./2.jpg"img_gray = cv2.imread(img_path, 0)# img_gray = cv2.resize(img_bgr, (224, 224))Y = np.arange(0, np.shape(img_gray)[0], 1)X = np.arange(0, np.shape(img_gray)[1], 1)X, Y = np.meshgrid(X, Y)fig = plt.figure()ax = plt.axes(projection="3d")ax.plot_surface(X, Y, img_gray, cmap='gist_rainbow') # cmap='hot'plt.show()
from mpl_toolkits.mplot3d import Axes3D
一定要加上,不加的话会报错
Traceback (most recent call last):File "D:\Anaconda\lib\site-packages\matplotlib\projections\__init__.py", line 58, in get_projection_classreturn projection_registry.get_projection_class(projection)File "D:\Anaconda\lib\site-packages\matplotlib\projections\__init__.py", line 25, in get_projection_classreturn self._all_projection_types[name]KeyError: '3d'During handling of the above exception, another exception occurred:Traceback (most recent call last):File "F:/Carrot_crack_Detection_segmentation/ceshi.py", line 17, in <module>ax = plt.axes(projection="3d")File "D:\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 877, in axesreturn subplot(111, **kwargs)File "D:\Anaconda\lib\site-packages\matplotlib\pyplot.py", line 1076, in subplota = fig.add_subplot(*args, **kwargs)File "D:\Anaconda\lib\site-packages\matplotlib\figure.py", line 1396, in add_subplotself._process_projection_requirements(*args, **kwargs)File "D:\Anaconda\lib\site-packages\matplotlib\figure.py", line 1120, in _process_projection_requirementsprojection_class = projections.get_projection_class(projection)File "D:\Anaconda\lib\site-packages\matplotlib\projections\__init__.py", line 60, in get_projection_classraise ValueError("Unknown projection %r" % projection)ValueError: Unknown projection '3d'Process finished with exit code 1
运行结果
cmap=‘hot’模式下的效果
cmap='gist_rainbow’下的显示效果
如果觉得《利用Python和OpenCV将图像灰度图转为3D图并显示》对你有帮助,请点赞、收藏,并留下你的观点哦!