Python + OpenCV:cv2.rectangle() 出現 TypeError: Scalar value for argument ‘color’ is not numeric
前言
之前使用Python都習慣裝3.6以上的版本,這幾天因為公司程式需要,所以用Anaconda裝了Python3.5的虛擬環境,結果跑之前的OpenCV程式會出現錯誤。
錯誤內容有兩個:
- 一個是寫參數’color’型態錯誤
TypeError: Scalar value for argument ‘color’ is not numeric
- 另一個也是型態錯誤,主要是位置錯誤
cv2.rectangle: TypeError: Argument given by name ('thickness') and position (4)
這兩個問題都是發生在cv2.rectangle
上面,明明在Python3.6就沒問題,怎麼降個版本結果差那麼多= ="。
Original issue
原本想說就照著上面的錯誤資訊去修改就好,結果一直不能成功,上網查了之後根本就不是什麼顏色參數的問題,而是繪製矩形的座標型態錯誤,完全被誤導。
sample_image = np.reshape(image * 255 , ( 96 , 96 ) ).astype( np.uint8 )
gd = label * 96
gd = gd.astype(np.int32)
gd = np.reshape(gd , ( 15 , 2 ) )
print(np.min(gd))
print(np.max(gd))
print(gd.shape)
#=========================================================#
# 在Python3.6中,我是直接用NumPy的function去取得我要繪製的點
# 結果在3.5中不能直接這樣輸入,必須要將其轉成Python的整數int型態
#=========================================================#
pt_1 = np.array([np.min(gd[ : , 0 ]), np.min(gd[ : , 1 ])])
pt_2 = np.array([np.max(gd[ : , 0 ]), np.max(gd[ : , 1 ])])
#=========================================================#
show_im = cv2.cvtColor(sample_image.T.copy(), cv2.COLOR_GRAY2BGR)
show_im = cv2.rectangle(show_im, pt_1, pt_2, (0,0,255))
plt.imshow(show_im)
plt.show()
Solution
sample_image = np.reshape(image * 255 , ( 96 , 96 ) ).astype( np.uint8 )
gd = label * 96
gd = gd.astype(np.int32)
gd = np.reshape(gd , ( 15 , 2 ) )
print(np.min(gd))
print(np.max(gd))
print(gd.shape)
#=========================================================#
# solution
# ----------
# 將NumPy的結果直接轉成Pyhon的整數int就可以解決。
#=========================================================#
gt_bbox = ( np.min(gd[:,0]) , np.min(gd[:,1]) , np.max(gd[:,0]) , np.max(gd[:,1]) )
x_min, y_min, x_max, y_max = map(int, gt_bbox)
#=========================================================#
show_im = cv2.cvtColor(sample_image.T.copy(), cv2.COLOR_GRAY2BGR)
cv2.rectangle(show_im, (x_min, y_min), (x_max, y_max), (255,0,0), thickness=1)
plt.imshow(show_im)
plt.show()