2021年5月4日 星期二

LabVIEW 利用 Python的OpenCV分析角度

 

題目:我使用LabVIEW 控制儀器,我需要判斷拍到的照片裡面方格偏轉的角度,Python 有很多現成的函式庫, 例如OpenCV, 我想要把圖從LabVIEW傳給Python, 再從Python去分析圖片偏轉的角度,再回傳給LabVIEW 去做平台角度的補償。

我拍的照片是8bits 灰階, 所以我把8bits的影像傳到python,再把這個8bits的影像整理成為nparray,再把nparray轉成OpenCV可以用的影像array

我參考了幾個範例,照片以及程式參閱附件



 1.Can a Python Node to Call a Function That Includes Python Packages?

#https://knowledge.ni.com/KnowledgeArticleDetails?id=kA03q000000ww92CAA&l=zh-TW for reference

2. Convert nparray to OpenCV

#https://stackoverflow.com/questions/7587490/converting-numpy-array-to-opencv-array

3.Detect angle and rotate an image in Python

#https://stackoverflow.com/questions/46731947/detect-angle-and-rotate-an-image-in-python/46732132




import numpy as np
from scipy import ndimage
import numpy as np
import cv2
import math

def function(lvarray,lvsize):
    Row_N=lvsize[0]
    Col_N=lvsize[1]
    #convert LabVIEW array into Numpy array
    #https://knowledge.ni.com/KnowledgeArticleDetails?id=kA03q000000ww92CAA&l=zh-TW for reference
    nparray =np.array(lvarray)
   
    new_image = np.ndarray((3,Row_N, Col_N), dtype=int)
    new_image[0,:,:]=nparray.reshape((Row_N, Col_N))
    new_image[1,:,:]=nparray.reshape((Row_N, Col_N))
    new_image[2,:,:]=nparray.reshape((Row_N, Col_N))

#Convert nparray to OpenCV
#https://stackoverflow.com/questions/7587490/converting-numpy-array-to-opencv-array
    
    #Converted the datatype to np.uint8
    new_image = new_image.astype(np.uint8)

    #Separated the channels in my new image
    new_image_red, new_image_green, new_image_blue = new_image

    #Stacked the channels
    new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

    img_before=new_rgb
    #Resize Image
    img_before = cv2.resize(img_before,(1040,776),interpolation=cv2.INTER_CUBIC)

#Detect angle and rotate an image in Python
#https://stackoverflow.com/questions/46731947/detect-angle-and-rotate-an-image-in-python/46732132

    cv2.imshow("Before", img_before)    
    key = cv2.waitKey(0)
    
    img_gray = cv2.cvtColor(img_before, cv2.COLOR_BGR2GRAY)
    img_edges = cv2.Canny(img_gray, 100, 100, apertureSize=3)
    lines = cv2.HoughLinesP(img_edges, 1, math.pi / 180.0, 100, minLineLength=70, maxLineGap=5)

    angles = []

    for [[x1, y1, x2, y2]] in lines:
        cv2.line(img_before, (x1, y1), (x2, y2), (255, 0, 0), 3)
        angle = math.degrees(math.atan2(y2 - y1, x2 - x1))
        
        if angle <=-45:
            angle = angle + 90
        else:
            if angle >=45:
                angle=angle-90
        
        angles.append(angle)

    cv2.imshow("Detected lines", img_before)    
    key = cv2.waitKey(0)

    mean_angle = np.mean(angles)

    return mean_angle


沒有留言: