資源簡介
傾斜圖像霍夫變換旋轉,并進行識別特定區域進行裁剪
代碼片段和文件信息
import?os
import?cv2
import?math
import?random
import?numpy?as?np
from?scipy?import?misc?ndimage
import?matplotlib.pyplot?as?plt
?
img?=?cv2.imread(‘D:/2.jpg‘)
#圖片路徑
gray?=?cv2.cvtColor(img?cv2.COLOR_BGR2GRAY)
edges?=?cv2.Canny(gray?50?150?apertureSize=3)
#?霍夫變換將圖片所在的直角坐標系中具有形狀的曲線或直線映射到霍夫空間的一個點上形成峰值,
#?從而將檢測任意形狀的問題轉化成了計算峰值的問題即在圖片所在的直角坐標系的一個直線
#?轉換到霍夫空間便成了一點,并且是由多條直線相交而成,我們統計的峰值也就是該相交點的橡膠線的條數
lines?=?cv2.HoughLines(edges?1?np.pi?/?180?0)
rotate_angle?=?0
for?rho?theta?in?lines[0]:
????a?=?np.cos(theta)
????b?=?np.sin(theta)
????x0?=?a?*?rho
????y0?=?b?*?rho
????x1?=?int(x0?+?1000?*?(-b))
????y1?=?int(y0?+?1000?*?(a))
????x2?=?int(x0?-?1000?*?(-b))
????y2?=?int(y0?-?1000?*?(a))
????if?x1?==?x2?or?y1?==?y2:
????????continue
????t?=?float(y2?-?y1)?/?(x2?-?x1)
#計算角度
????rotate_angle?=?math.degrees(math.atan(t))
????if?rotate_angle?>?45:
????????rotate_angle?=?-90?+?rotate_angle
????elif?rotate_angle?-45:
????????rotate_angle?=?90?+?rotate_angle
print(“rotate_angle?:?“+str(rotate_angle))
rotate_img?=?ndimage.rotate(img?rotate_angle)
cv2.imshow(“img“?rotate_img)
cv2.imwrite(“new.jpg“?rotate_img)
cv2.waitKey(0)
image?=?cv2.imread(“new.jpg“)
gray?=?cv2.cvtColor(image?cv2.COLOR_BGR2GRAY)
?
#用Sobel算子計算x,y方向上的梯度,之后在x方向上減去y方向上的梯度,通過這個減法,我們留下具有高水平梯度和低垂直梯度的圖像區域。
gradX?=?cv2.Sobel(gray?cv2.CV_32F?dx=1?dy=0?ksize=-1)
gradY?=?cv2.Sobel(gray?cv2.CV_32F?dx=0?dy=1?ksize=-1)
?
gradient?=?cv2.subtract(gradX?gradY)
gradient?=?cv2.convertScaleAbs(gradient)
cv2.imshow(“first“?gradient)
cv2.waitKey()
?
#?
評論
共有 條評論