Python中的图像处理时的UnicodeDecodeError

时间:2016-12-24 08:23:47

标签: python opencv image-processing matplotlib

我正在使用Python 2.7.12中的OpenCV Canny Edge Detection。导入matplotlib后,我遇到以下错误:

> **File "C:\Python27\lib\site-packages\matplotlib\font_manager.py", line 398, in ttfFontProperty
    sfnt4 = sfnt4.decode('ascii').lower()
UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 0: ordinal not in range(128)**

我已经找到了答案,但在处理图像时似乎找不到解决方案。这是我的代码:

import numpy as np
import cv2
from matplotlib import pyplot as plt
import sys

#read image from file specified
img = cv2.imread('test.tif', cv2.IMREAD_COLOR);

#define display window name
windowname = "Image Segmentation";

#check if image has loaded
if not img is None:
    edges = cv2.Canny(img,100,200)
    plt.subplot(121),plt.imshow(img,cmap = 'gray')
    plt.title('Original Image'), plt.xticks([]), plt.yticks([])
    plt.subplot(122),plt.imshow(edges,cmap = 'gray')
    plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
    plt.show()

    #start the event loop - essential
    #cv2.waitKey() is a keyboard binding function (argument is time in ms).
    #if you press any key in that time, the program continues.
    #if 0 is passed, it waits indefinitely for a key stroke

    key = cv2.waitKey(0);

    #It can also be set to detect specific key strokes by recording which     key is pressed

    if (key == ord('x')):
        cv2.destroyAllWindows();

else:
    print ("No image file successfully loaded");**

1 个答案:

答案 0 :(得分:2)

.tif图像(字体部分)中似乎存在非ASCII属性,您的matplotlib库版本不支持。

在Python 3.4的matplotlib包中,我在C:\Python34\lib\site-packages\matplotlib\font_manager.py中有以下代码:

if sfnt4:
    sfnt4 = sfnt4.decode('macroman').lower()

解码包含非ascii字符的字体名称。

编辑:您似乎只需要更新matplotlib包:

pip install --upgrade matplotlib

我为python 2.7安装了最新的matplotlib(这是奉献:))并且编码已经切换到macroman,所以只需升级即可解决您的问题。