Skip to content

Commit

Permalink
feat: add some article
Browse files Browse the repository at this point in the history
  • Loading branch information
fiqgant committed Jul 7, 2024
1 parent 44f97fe commit 745b2b3
Show file tree
Hide file tree
Showing 20 changed files with 534 additions and 149 deletions.
11 changes: 9 additions & 2 deletions apps/docs/src/components/mdx/mdx.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { type MDXComponents, MDXRemote } from '@tszhong0411/mdx'
import * as uiComponents from '@tszhong0411/ui'
import { cn } from '@tszhong0411/utils'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'
import { type Pluggable } from 'unified'

import 'katex/dist/katex.min.css'
import { rehypeComponentCode } from '@/lib/rehype-component-code'

import ComponentPreview from './component-preview'
Expand All @@ -13,7 +17,6 @@ type MdxProps = {
const components: MDXComponents = {
...uiComponents,
ComponentPreview,

pre: uiComponents.CodeBlock
}

Expand All @@ -26,7 +29,11 @@ const Mdx = (props: MdxProps) => {
source={content}
components={components}
mdxOptions={{
rehypePlugins: [rehypeComponentCode]
remarkPlugins: [remarkMath as unknown as Pluggable],
rehypePlugins: [
rehypeComponentCode as unknown as Pluggable,
rehypeKatex as unknown as Pluggable
]
}}
/>
</div>
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
4 changes: 2 additions & 2 deletions apps/web/src/app/blog/[slug]/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ const Header = () => {
<div className='grid grid-cols-2 text-sm max-md:gap-4 md:grid-cols-4'>
<div className='space-y-1 md:mx-auto'>
<div className='text-muted-foreground'>Written by</div>
<Link href='https://github.com/tszhong0411' className='flex items-center gap-2'>
<Link href='https://github.com/fiqgant' className='flex items-center gap-2'>
<BlurImage
src='/images/avatar.png'
className='rounded-full'
width={24}
height={24}
alt='Hong'
/>
Hong
fiq
</Link>
</div>
<div className='space-y-1 md:mx-auto'>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
---
title: An Introduction to Linear Discriminant Analysis
date: '2024-07-07T00:00:00Z'
modifiedTime: '2024-07-07T00:00:00Z'
summary: Understanding and implementing Linear Discriminant Analysis for dimensionality reduction and classification.
---

## Preface

Linear Discriminant Analysis (LDA) is a fundamental technique in statistics and machine learning for dimensionality reduction and classification. It aims to model the difference between classes by finding a linear combination of features that characterizes or separates two or more classes. In this blog, we will explore the principles of LDA, its mathematical formulation, and how to implement it in Python.

![Linear Discriminant Analysis](https://www.researchgate.net/publication/288002528/figure/fig5/AS:318622703603716@1452976980713/Linear-discriminant-analysis.png)

## Demo

In this tutorial, we will demonstrate the implementation of LDA using Python and the scikit-learn library.

## How to Implement Linear Discriminant Analysis

First, ensure you have the necessary libraries installed:

```bash title='Terminal'
pip install numpy pandas scikit-learn matplotlib
```

Next, we will create a Python script to perform LDA.

### Importing Libraries and Dataset

We begin by importing the required libraries and loading the dataset.

```python title='lda_example.py'
import numpy as np
import pandas as pd
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt

# Load the dataset
data = pd.read_csv('your_dataset.csv')
```

### Preparing the Data

Split the data into features and target variables and then into training and testing sets.

```python title='lda_example.py'
# Assuming the last column is the target variable
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values

# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```

### Applying Linear Discriminant Analysis

Create an LDA object and fit it to the training data.

```python title='lda_example.py'
# Create an LDA object
lda = LDA()

# Fit the LDA model to the training data
lda.fit(X_train, y_train)

# Transform the data
X_train_lda = lda.transform(X_train)
X_test_lda = lda.transform(X_test)
```

### Evaluating the Model

Predict the target variable for the test set and calculate the accuracy.

```python title='lda_example.py'
# Predict the test set results
y_pred = lda.predict(X_test)

# Calculate the accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy * 100:.2f}%')
```

### Visualizing the Results

If the dataset is reduced to 2D or 3D, we can visualize the transformed data.

```python title='lda_example.py'
# Plot the transformed data
plt.figure(figsize=(10, 7))
colors = ['r', 'g', 'b']
for i, color in zip(np.unique(y_train), colors):
plt.scatter(X_train_lda[y_train == i, 0], X_train_lda[y_train == i, 1], c=color, label=f'Class {i}')
plt.title('LDA: Training Data Projection')
plt.xlabel('LD1')
plt.ylabel('LD2')
plt.legend(loc='best')
plt.show()
```

### Conclusion

Linear Discriminant Analysis is a powerful tool for both dimensionality reduction and classification. By projecting data onto a lower-dimensional space, LDA maximizes the class separability, making it easier to visualize and classify data. This tutorial has demonstrated the basic steps to implement LDA in Python using the scikit-learn library. For more advanced usage, consider exploring LDA with different datasets and parameter tuning.

## Useful links

- [Scikit-learn LDA Documentation](https://scikit-learn.org/stable/modules/lda_qda.html)
- [Linear Discriminant Analysis](https://en.wikipedia.org/wiki/Linear_discriminant_analysis)
- [Python Data Science Handbook](https://jakevdp.github.io/PythonDataScienceHandbook/)

Feel free to reach out with any questions or comments about this tutorial!
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
---
title: Face Counting using Haarcascade and YOLOv3
date: '2024-07-07T00:00:00Z'
modifiedTime: '2024-07-07T00:00:00Z'
summary: Implementing a face counting system by combining Haarcascade and YOLOv3 in Python.
---

## Preface

This blog will guide you through creating a face counting system using Haarcascade and YOLOv3. The system reads a video file, detects faces using both methods, and counts the faces only when the bounding boxes of both algorithms intersect.

The repository for this tutorial:

https://github.com/fiqgant/face_counting_haarcascade_yolov3

## Project Structure

<Files>
<Folder name='models' defaultOpen>
<File name='haarcascade_frontalface_default.xml' />
<File name='yolov3.onnx' />
</Folder>
<Folder name='scripts' defaultOpen>
<File name='face_counting.py' />
</Folder>
<Folder name='videos' defaultOpen>
<File name='video.mp4' />
</Folder>
</Files>

## How to Create the Face Counting System

First, ensure you have the necessary libraries installed:

```bash title='Terminal'
pip install numpy opencv-python opencv-python-headless onnxruntime
```

Next, we will create a Python script to implement the face counting system.

### Importing Libraries and Loading Models

We begin by importing the required libraries and loading the Haarcascade and YOLOv3 models.

```python title='face_counting.py'
import cv2
import numpy as np
import onnxruntime as ort

# Load the Haarcascade model
haarcascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Load the YOLOv3 model
ort_session = ort.InferenceSession('yolov3.onnx')
input_name = ort_session.get_inputs()[0].name
```

### Processing the Video

Read the video file and initialize variables for counting faces.

```python title='face_counting.py'
# Read the video file
cap = cv2.VideoCapture('video.mp4')

# Initialize the face count
face_count = 0
```

### Detecting Faces

Create functions to detect faces using Haarcascade and YOLOv3.

```python title='face_counting.py'
def detect_faces_haarcascade(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = haarcascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
return faces

def detect_faces_yolo(frame):
blob = cv2.dnn.blobFromImage(frame, 1/255.0, (416, 416), swapRB=True, crop=False)
ort_inputs = {input_name: blob}
detections = ort_session.run(None, ort_inputs)
faces = []
for detection in detections[0]:
confidence = detection[4]
if confidence > 0.5:
x, y, w, h = (detection[0:4] * np.array([frame.shape[1], frame.shape[0], frame.shape[1], frame.shape[0]])).astype(int)
faces.append((x, y, w, h))
return faces
```

### Counting Faces

Process each frame of the video and count the faces only if both Haarcascade and YOLOv3 detect and intersect the same face.

```python title='face_counting.py'
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break

# Detect faces using both methods
faces_haarcascade = detect_faces_haarcascade(frame)
faces_yolo = detect_faces_yolo(frame)

# Count faces based on intersection of both methods
for (x1, y1, w1, h1) in faces_haarcascade:
for (x2, y2, w2, h2) in faces_yolo:
if (x1 < x2 + w2 and x1 + w1 > x2 and y1 < y2 + h2 and y1 + h1 > y2):
face_count += 1
cv2.rectangle(frame, (x1, y1), (x1 + w1, y1 + h1), (0, 255, 0), 2)
break

cv2.imshow('Face Counting', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

cap.release()
cv2.destroyAllWindows()
print(f'Total faces counted: {face_count}')
```

### Conclusion

This tutorial demonstrated how to create a face counting system by combining Haarcascade and YOLOv3. By leveraging the strengths of both methods, we can achieve more accurate face detection and counting. Feel free to explore the [GitHub repository](https://github.com/fiqgant/face_counting_haarcascade_yolov3) for more details and additional functionalities.

## Useful links

- [OpenCV Documentation](https://docs.opencv.org/)
- [YOLOv3 Documentation](https://pjreddie.com/darknet/yolo/)
- [ONNX Runtime Documentation](https://onnxruntime.ai/docs/)

Feel free to reach out with any questions or comments about this tutorial!
Loading

0 comments on commit 745b2b3

Please sign in to comment.