線性回歸(Linear Regression)

首先,使用make_regression函數生成了一些合成數據,然後將數據分成訓練集和測試集。接著創建了LinearRegression模型的實例,並使用訓練集對模型進行訓練。訓練完成後,打印出了模型的係數和對新數據的預測結果。最後,通過可視化將訓練集和測試集的散點圖以及線性回歸的平面呈現出來。

import numpy as np
import matplotlib.pyplot as mpl
from mpl_toolkits.mplot3d import Axes3D
from sklearn import linear_model
from sklearn.datasets import make_regression

# Generating synthetic data for training and testing
X, y = make_regression(n_samples=100, n_features=2, n_informative=1, random_state=0, noise=50)

# X and y are values for 3D space. We first need to train
# the machine, so we split X and y into X_train, X_test,
# y_train, and y_test. The *_train data will be given to the 
# model to train it.
X_train, X_test = X[:80], X[-20:]
y_train, y_test = y[:80], y[-20:]

# Creating instance of model
regr = linear_model.LinearRegression()

# Training the model 
regr.fit(X_train, y_train)

# Printing the coefficients 
print(regr.coef_)
# [-10.25691752 90.5463984 ]
# Predicting y-value based on training 
X1 = np.array([1.2, 4])
print(regr.predict([X1]))
# 350.860363861
# With the *_test data we can see how the result matches 
# the data the model was trained with.
# It should be a good match as the *_train and *_test
# data come from the same sample. Output: 1 is perfect
# prediction and anything lower is worse. 
print(regr.score(X_test, y_test))
# 0.949827492261

fig = mpl.figure(figsize=(8, 5))
ax = fig.add_subplot(111, projection='3d') 
ax.view_init(elev=20, azim=0)
# ax = Axes3D(fig)
# Data
ax.scatter(X_train[:,0], X_train[:,1], y_train, facecolor='#00CC00') 
ax.scatter(X_test[:,0], X_test[:,1], y_test, facecolor='#FF7800')

# Function with coefficient variables
coef = regr.coef_
line = lambda x1, x2: coef[0] * x1 + coef[1] * x2
grid_x1, grid_x2 = np.mgrid[-2:2:10j, -2:2:10j] 
ax.plot_surface(grid_x1, grid_x2, line(grid_x1, grid_x2), alpha=0.1, color='k') 
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.zaxis.set_visible(False)
分類: AI, AOI | 標籤: , | 發佈留言

密度聚類算法(DBSCAN)

DBSCAN(Density-Based Spatial Clustering of Applications with Noise)是一種密度聚類算法,用於將數據點劃分為多個集群,同時可以識別和排除噪音點。該算法基於以下概念:

  1. 核心點(Core Points):對於給定的半徑 $\varepsilon$ (epsilon)內至少包含 $min_samples$ 個數據點的點被視為核心點。
  2. 邊界點(Border Points):如果一個點不是核心點,但位於某個核心點的 $\varepsilon$ 鄰域內,則它被視為邊界點。
  3. 噪音點(Noise Points):不是核心點也不是邊界點的數據點被視為噪音點。

DBSCAN算法運行步驟如下:

  1. 選擇一個未訪問的數據點作為起始點,檢查其 $\varepsilon$ 鄰域內的點數量:
    • 如果該點是核心點,則將其與其 $\varepsilon$ 鄰域內的所有點標記為同一個集群。
    • 如果該點是邊界點,則將其標記為集群的一部分。
  2. 對於已訪問的核心點,擴展集群並標記所有可達的點。
  3. 重複步驟1和步驟2,直到所有點都被訪問過。

DBSCAN的主要優勢是:

  • 能夠在集群之間具有不同的形狀和大小。
  • 能夠識別和排除噪音點。
  • 不需要事先指定要劃分的集群數量。

總的來說,DBSCAN是一種強大的聚類算法,特別適用於處理具有不同密度和形狀的數據集。

import numpy as np
import matplotlib.pyplot as mpl 
from scipy.spatial import distance 
from sklearn.cluster import DBSCAN
# Creating data
c1 = np.random.randn(100, 2) + 5 
c2 = np.random.randn(50, 2)
# Creating a uniformly distributed background
u1 = np.random.uniform(low=-10, high=10, size=100) 
u2 = np.random.uniform(low=-10, high=10, size=100) 
c3 = np.column_stack([u1, u2])
# Pooling all the data into one 150 x 2 array 
data = np.vstack([c1, c2, c3])

# Calculating the cluster with DBSCAN function.
# db.labels_ is an array with identifiers to the 
# different clusters in the data.
#db = DBSCAN().fit(data, eps=0.95, min_samples=10) 
db = DBSCAN().fit(data) 
labels = db.labels_
# Retrieving coordinates for points in each
# identified core. There are two clusters
# denoted as 0 and 1 and the noise is denoted 
# as -1. Here we split the data based on which 
# component they belong to.
dbc1 = data[labels == 0]
dbc2 = data[labels == 1]
noise = data[labels == -1]
# Setting up plot details 
x1, x2 = -12, 12
y1, y2 = -12, 12
fig = mpl.figure() 
fig.subplots_adjust(hspace=0.1, wspace=0.1)
ax1 = fig.add_subplot(121, aspect='equal') 
ax1.scatter(c1[:,0], c1[:,1], lw=0.5, color='#00CC00') 
ax1.scatter(c2[:,0], c2[:,1], lw=0.5, color='#028E9B') 
ax1.scatter(c3[:,0], c3[:,1], lw=0.5, color='#FF7800') 
ax1.xaxis.set_visible(False) 
ax1.yaxis.set_visible(False)
ax1.set_xlim(x1, x2)
ax1.set_ylim(y1, y2)
ax1.text(-11, 10, 'Original')
ax2 = fig.add_subplot(122, aspect='equal') 
ax2.scatter(dbc1[:,0], dbc1[:,1], lw=0.5, color='#00CC00') 
ax2.scatter(dbc2[:,0], dbc2[:,1], lw=0.5, color='#028E9B') 
ax2.scatter(noise[:,0], noise[:,1], lw=0.5, color='#FF7800') 
ax2.xaxis.set_visible(False)
ax2.yaxis.set_visible(False)
ax2.set_xlim(x1, x2)
ax2.set_ylim(y1, y2)
ax2.text(-11, 10, 'DBSCAN identified')
分類: AI, AOI | 標籤: , , | 發佈留言

自適應或動態閾值化(Dynamic Threshold)

在影像科學中的一個常見應用是將圖像組件從彼此分割開來,這稱為閾值化。傳統的閾值化技術在圖像的背景是平坦的情況下效果很好。不幸的是,這種情況並不常見;相反,圖像中的背景在視覺上會在整個圖像中發生變化。因此,人們開發了自適應閾值化技術,我們可以很容易地在 scikit-image 中使用它們。

import numpy as np
import matplotlib.pyplot as mpl 
import scipy.ndimage as ndimage 
import skimage.filters as skif
import matplotlib.pyplot as plt
# Generating data points with a non-uniform background
x = np.random.uniform(low=0, high=100, size=20).astype(int) 
y = np.random.uniform(low=0, high=100, size=20).astype(int)
# Creating image with non-uniform background 
func = lambda x, y: x**2 + y**2
grid_x, grid_y = np.mgrid[-1:1:100j, -2:2:100j] 
bkg = func(grid_x, grid_y)
bkg = bkg / np.max(bkg)
# Creating points
clean = np.zeros((100,100))
clean[(x,y)] += 5
clean = ndimage.gaussian_filter(clean, 3) 
clean = clean / np.max(clean)
# Combining both the non-uniform background 
# and points
fimg = bkg + clean
fimg = fimg / np.max(fimg)

# Defining minimum neighboring size of objects 
block_size = 3
# Adaptive threshold function which returns image
# map of structures that are different relative to
# background
adaptive_cut = fimg > skif.threshold_local(fimg, block_size, 'gaussian')

# Global threshold
global_thresh = skif.threshold_otsu(fimg) 
global_cut = fimg > global_thresh

# Creating figure to highlight difference between 
# adaptive and global threshold methods
fig = mpl.figure(figsize=(8, 4)) 
fig.subplots_adjust(hspace=0.05, wspace=0.05)

ax1 = fig.add_subplot(131) 
ax1.imshow(fimg, cmap='gray') 
ax1.xaxis.set_visible(False) 
ax1.yaxis.set_visible(False)

ax2 = fig.add_subplot(132) 
ax2.imshow(global_cut, cmap='gray') 
ax2.xaxis.set_visible(False) 
ax2.yaxis.set_visible(False)

ax3 = fig.add_subplot(133) 
ax3.imshow(adaptive_cut, cmap='gray') 
ax3.xaxis.set_visible(False) 
ax3.yaxis.set_visible(False)
分類: AOI | 標籤: | 發佈留言

稀疏矩陣(SparseMatrices)

稀疏矩陣相對於密集矩陣在處理大多數元素為零的大型數組時的效率。稀疏矩陣僅存儲非零元素及其位置,導致在某些操作中記憶體使用量和計算時間大幅減少。

import numpy as np
from scipy.sparse.linalg import eigsh 
from scipy.linalg import eigh
import scipy.sparse
import time
N = 3000
# Creating a random sparse matrix 
m = scipy.sparse.rand(N, N)
# Creating an array clone of it 
a = m.toarray()
print('The numpy array data size: ' + str(a.nbytes) + ' bytes') 
print('The sparse matrix data size: ' + str(m.data.nbytes) + ' bytes')
# Non-sparse
t0 = time.time()
res1 = eigh(a)
dt = str(np.round(time.time() - t0, 3)) + ' seconds' 
print('Non-sparse operation takes ' + dt)
# Sparse
t0 = time.time()
res2 = eigsh(m)
dt = str(np.round(time.time() - t0, 3)) + ' seconds' 
print('Sparse operation takes ' + dt)
分類: AI | 標籤: , | 發佈留言

Scipy Vector Quantization (向量量化)

向量量化是一個通用術語,可以與信號處理、數據壓縮和聚類相關聯。在這裡,我們將專注於聚類組件,從如何將數據提供給vq包以識別聚類開始。

import numpy as np
from scipy.cluster import vq
# Creating data
c1 = np.random.randn(100, 2) + 5 
c2 = np.random.randn(30, 2) - 5 
c3 = np.random.randn(50, 2)
# Pooling all the data into one 180 x 2 array 
data = np.vstack([c1, c2, c3])
# Calculating the cluster centroids and variance 
# from kmeans
centroids, variance = vq.kmeans(data, 3)
# The identified variable contains the information 
# we need to separate the points in clusters
# based on the vq function.
identified, distance = vq.vq(data, centroids)
# Retrieving coordinates for points in each vq 
# identified core
vqc1 = data[identified == 0]
vqc2 = data[identified == 1]
vqc3 = data[identified == 2]
# Plotting the clustered data points and centroids
plt.figure(figsize=(8, 6))
plt.scatter(vqc1[:, 0], vqc1[:, 1], c='red', label='Cluster 1')
plt.scatter(vqc2[:, 0], vqc2[:, 1], c='blue', label='Cluster 2')
plt.scatter(vqc3[:, 0], vqc3[:, 1], c='green', label='Cluster 3')
plt.scatter(centroids[:, 0], centroids[:, 1], c='black', marker='x', s=100, label='Centroids')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Clustered Data with Centroids')
plt.legend()
plt.grid(True)
plt.show()
分類: AI | 標籤: , | 發佈留言

Scipy常態分佈(normal distribution)

在SciPy的stats模塊中,norm代表正態分佈,也被稱為高斯分佈。正態分佈是一種連續概率分佈,其在平均值周圍對稱。

SciPy中的norm對象表示具有指定均值(loc)和標準差(scale)的正態分佈。它提供了各種方法來處理正態分佈,例如計算概率密度函數(PDF)、累積分佈函數(CDF)、生成隨機樣本等。

在提供的代碼中,norm用於創建一個具有均值(loc)為0和標準差(scale)為1的正態分佈對象。然後,使用這個分佈對象(dist)計算PDF、CDF,並從正態分佈生成隨機樣本。

import numpy as np
from scipy.stats import norm
x = np.linspace(-5, 5, 1000)
dist = norm(loc=0, scale=1)
pdf = dist.pdf(x)
cdf = dist.cdf(x)
sample = dist.rvs(500)
# Plot PDF
plt.figure(figsize=(10, 6))
plt.plot(x, pdf, label='PDF')

# Plot CDF
plt.plot(x, cdf, label='CDF')

# Plot histogram of samples
plt.hist(sample, bins=30, density=True, alpha=0.5, label='Sample Histogram')

# Add labels and legend
plt.xlabel('x')
plt.ylabel('Probability')
plt.title('PDF, CDF, and Sample Histogram of Normal Distribution')
plt.legend()

# Show plot
plt.grid(True)
plt.show()

在這個例子中,pdfcdf 是根據模型預測的值,而 sample 是隨機模擬出的值,用於檢驗模型與實際數據的符合程度。

PDF 與 sample的分佈是一致。CDF(累積分佈函數)代表的是在某個數值之前的累積概率。對於正態分佈來說,當 x 值由-5往0時越接近平均值,累積概率越接近 0.5,這是因為正態分佈是對稱的, CDF在 x > 0 的區間,CDF 的值持續上升,而是趨於 1。這種情況下,如果模型的預測與實際數據相符,並且實際數據的分佈也表現出在這個區間的數值較大的趨勢,那麼可以認為模型是比較正確的

分類: AI | 標籤: , | 發佈留言

內插法(Interpolation)

內插法是一種數學方法,用於在已知數據點之間估算未知點的值。在內插中,我們假設數據點之間的關係是連續且光滑的,並使用這種關係來預測未知位置的數值。

具體來說,當我們有一組離散的數據點,但我們想要在這些點之間的某個位置獲得更多的數據時,我們就可以使用內插法。它通常用於曲線擬合和數據補充的情況下,幫助我們理解數據的行為、預測趨勢或填補缺失的數據。

在內插中,我們根據已知的數據點來建立一個函數或曲線,該函數或曲線在這些點上通過已知的數據點,並且在這些點之間是連續且光滑的。然後,我們使用這個函數或曲線來估算我們感興趣的位置的值。

內插法有很多種類,包括線性內插、多項式內插、樣條內插等。選擇適當的內插方法取決於數據的特性和應用的需求

SciPy提供了十幾種不同的插值函數,從簡單的單變量情況到複雜的多變量情況。當樣本數據可能由一個獨立變量引導時,使用單變量插值,而多變量插值則假設存在多個獨立變量。 內插法有兩種基本方法:(1)對整個數據集擬合一個函數或(2)用多個函數擬合數據集的不同部分,其中每個函數的連接部分平滑地連接在一起。

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

#產生已知數據
x = np.linspace(0, 10 * np.pi, 20)
y = np.cos(x)

#使用線性內插(擬合),得到f1線性函式
f1 = interp1d(x, y, kind='linear')

#使用二次內插(擬合),得到fq二次函式
fq = interp1d(x, y, kind='quadratic')

#尋找兩個函式間的交點,初始猜測值(x點座標)
result = findIntersection(f1, fq, [0, 5, 10, 15, 20, 25, 30])

xint = np.linspace(x.min(), x.max(), 1000)
plt.ylim(-1.5, 2)
plt.plot(x, y, label='cos')
plt.plot(xint, f1(xint), label='linear')
plt.plot(xint, fq(xint), label='quadratic')
plt.plot(result, fq(result), 'ro', markerfacecolor='none')
plt.legend(loc='upper left')
plt.show()

我們接下來使用一個複雜的邏輯來產生數據,再使用Scipy的內插(擬合)函式來找出合適的資料模型函式。

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
from scipy.optimize import fsolve

#尋找兩函式的交點
def findIntersection(func1, func2, sample, x0):
    return fsolve(lambda x: func1(x) - func2(x, sample), x0)
    
sample = 30

#更複雜的函式
x = np.linspace(1, 10 * np.pi, sample)
def func(x, sample):
    return np.cos(x) + np.log10(x) + np.random.randn(sample) / 10 
y = func(x, sample)

#一元二次樣條函式
f = UnivariateSpline(x, y, s=1)

#尋找兩函式的交點
result = findIntersection(f, func, 6, [5, 10, 15, 20, 25, 30])


xint = np.linspace(x.min(), x.max(), 1000)
plt.plot(x, y, label='origin')
plt.plot(xint, f(xint), label='UnivariateSpline')
plt.plot(result, f(result), 'ro', markerfacecolor='none')
plt.legend()
plt.show()
import numpy as np
from scipy.interpolate import griddata

# Defining a function
ripple = lambda x, y: np.sqrt(x**2 + y**2)+np.sin(x**2 + y**2)

# Generating gridded data. The complex number defines
# how many steps the grid data should have. Without the
# complex number mgrid would only create a grid data structure # with 5 steps.
grid_x, grid_y = np.mgrid[0:5:1000j, 0:5:1000j]

# Generating sample that interpolation function will see 
xy = np.random.rand(1000, 2)
sample = ripple(xy[:,0] * 5 , xy[:,1] * 5)

# Interpolating data with a cubic
# griddata 是 SciPy 中的一個函數,用於在非結構化的數據點集上進行插值。當你有一組數據點,但## #它們不是均勻分佈在網格上時,你可以使用 griddata 將這些數據點的值插值到指定的網格上,以獲得在整個網格上的連續數值。

# 具體來說,griddata 函數接受三個主要的參數:

# points:數據點的坐標。
# values:對應於每個數據點的值。
# grid:指定用於插值的目標網格。
# griddata 根據給定的數據點和對應的值,在目標網格上進行插值,並返回整個網格上的插值結果。插值方法可以通過 method 參數指定,包括線性插值、最近鄰插值和立方插值等。


grid_z0 = griddata(xy * 5, sample, (grid_x, grid_y), method='cubic')

# 繪製內插後的圖像
plt.ylim(0, 6)
plt.xlim(0, 6)
plt.imshow(grid_z0, extent=(0, 5, 0, 5), origin='lower', cmap='viridis')

# 添加色標
plt.colorbar()

# 繪製樣本數據的散點圖
plt.scatter(xy[:, 0] * 5, xy[:, 1] * 5, c=sample, cmap='Reds', label='Sample Data', s=1)

# 添加標籤和標題
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interpolated Data with Sample Points')
plt.legend(loc='upper left')

# 顯示圖像
plt.show()
分類: AI | 標籤: , , | 發佈留言

影像清晰度分析

客戶需求:希望視覺檢測系統回饋影像的清晰度的數值。

判斷畫面是否清晰或模糊的方式可以有多種,以下是一些常見的方法:

  • 拉普拉斯變異數(Laplacian Variance):這是一種常見的方法,通過計算圖像的拉普拉斯變異數來衡量圖像的清晰度。拉普拉斯變異數越高,表示圖像越清晰。
  • 頻譜能量(Spectral Energy):該方法計算圖像的頻譜能量,即圖像中的高頻成分。如果圖像具有較多的高頻成分,則認為圖像較清晰。
  • 對比度(Contrast):衡量圖像中亮度差異的程度。如果圖像具有較高的對比度,則通常認為圖像較清晰。
  • 主動輪廓(Active Contours):這種方法使用主動輪廓模型來擬合圖像中的對象,並計算擬合的程度。如果對象較清晰地擬合於圖像中,則認為圖像較清晰。
  • 高通濾波器(High-pass Filtering):通過應用高通濾波器來突出圖像中的邊緣和細節,以評估圖像的清晰度。

這些方法中的每一種都有其優缺點,並且在不同的應用場景下可能表現不同。通常,人們會根據具體的應用需求和特定的圖像特徵來選擇合適的方法。

實驗結果: 可以看到相片左上角的數值變化,數值越大越清晰 

分類: 未分類 | 發佈留言

Jenkins Docker-Compose.yml

version: '3.3'
services:
    jenkins:
        image: jenkins/jenkins:lts
        restart: unless-stopped
        privileged: true
        user: root
        ports:
        - 8080:8080
        container_name: jenkins
        volumes:
        - ./jenkins:/var/jenkins_home
        - /var/run/docker.sock:/var/run/docker.sock
        - /usr/local/bin/docker:usr:/usr/local/bin/docker

docker-compose up -d 運行 jenkins

docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword

分類: 未分類 | 發佈留言

多光譜影像處理

使用多光譜影像處理或多光譜成像技術。它是一種利用不同波長的光(通常是可見光和近紅外光)來拍攝影像的技術。通過拍攝多個波長的影像,可以獲得不同光譜的信息,從而提供更多的資訊來分析和理解影像中的物體。

使用了三種不同顏色及不同的角度(紅光、綠光、藍光)的光來照射工件,並使用黑白相機分別拍攝了這三種光照下的影像。然後將這三張黑白照片組合成RGB彩色影像。在這個過程中,由於工件上的凸起部分對不同波長的光反射的方式不同,因此在RGB彩色影像中會出現顏色的變化。

多光譜成像技術可應用於許多領域,包括農業、環境監測、醫學影像、地質勘探等,以提供更多的資訊和更全面的分析。

使用案例: 檢測PCB板上的插件

RGB
R, G, B Merge RGBPost Process

後處理後的影像,可以很清楚的辨識插件是否有正確的組裝。

分類: AOI | 標籤: | 發佈留言