1602667037
How often do you feel like getting yourself sketched by an artist? Well say no more, now you can easily make the use of OpenCV and make your own sketch within few minutes. Just in 4 steps OpenCV will provide you with the portrait of the same.
Okay let’s dive right into it and make yourself a sketch without picking up a brush.
So for this particular task we are going to use Google Colaboratory or “Colab” for short which allows you to write and execute Python in your browser with Zero configuration required, free access to GPUs and easy sharing.
Well, you can either use Jupyter Notebook for the same, it’s totally your call.
The four steps which we are going to use today are as follows:
#opencv #computer-vision #python
1591743681
Learn Free how to create a virtual pen and eraser with python and OpenCV with source code and complete guide. This entire application is built fundamentally on contour detection. It can be thought of as something like closed color curves on compromises that have the same color or intensity, it’s like a blob. In this project we use color masking to get the binary mask of our target color pen, then we use the counter detection to find the location of this pen and the contour to find it.
#python #create virtual pen and eraser with opencv #create virtual pen and eraser with python opencv #programming #opencv #python opencv
1614145832
It’s 2021, everything is getting replaced by a technologically emerged ecosystem, and mobile apps are one of the best examples to convey this message.
Though bypassing times, the development structure of mobile app has also been changed, but if you still follow the same process to create a mobile app for your business, then you are losing a ton of opportunities by not giving top-notch mobile experience to your users, which your competitors are doing.
You are about to lose potential existing customers you have, so what’s the ideal solution to build a successful mobile app in 2021?
This article will discuss how to build a mobile app in 2021 to help out many small businesses, startups & entrepreneurs by simplifying the mobile app development process for their business.
The first thing is to EVALUATE your mobile app IDEA means how your mobile app will change your target audience’s life and why your mobile app only can be the solution to their problem.
Now you have proposed a solution to a specific audience group, now start to think about the mobile app functionalities, the features would be in it, and simple to understand user interface with impressive UI designs.
From designing to development, everything is covered at this point; now, focus on a prelaunch marketing plan to create hype for your mobile app’s targeted audience, which will help you score initial downloads.
Boom, you are about to cross a particular download to generate a specific revenue through your mobile app.
#create an app in 2021 #process to create an app in 2021 #a complete process to create an app in 2021 #complete process to create an app in 2021 #process to create an app #complete process to create an app
1649237810
If you want your business to prosper, you'll have to stay on top of the latest trends. The creation of a chatbot is a lengthy procedure. However, if well planned, it can be a piece of cake. The emergence of chatbots is one of the most significant recent developments in the area of customer care. On that topic, chatbots are one of the most well-known marketing tools in use today, aiding in the development of effective communication between businesses and their customers. So, read on to learn about data science projects for final year students as well as data science projects for beginners.
When it comes to chatbot creation, the most important thing to remember is to break the process down into simple steps and follow them one by one. Chatbots are quite handy if you want to improve your customer's experience by answering their questions, reducing human workload, performing remote troubleshooting, and so on. Rather than adopting a bot development framework or another platform, why not build a basic, intelligent chatbot from the ground up using deep learning? Though bots have a wide range of applications, one of the most well-known is live chat platforms, where users ask queries and a chatbot responds appropriately. There are different types of recommendation systems of the data science projects ideas.
So, in order to make your life easier, we've provided step-by-step chatbot programming guidelines. The days of waiting (not so patiently) on hold for answers to your most pressing questions are quickly fading away. In this lesson, you'll learn how to use Keras to create an end-to-end domain-specific intelligent chatbot solution.
Overview:
A chatbot is a piece of software that can communicate and conduct tasks in the same way that a human can. Because we're going to build a deep learning model, we'll need data to train it. Chatbots are marketing and automation solutions that are supposed to assist people by interacting with them and performing human-like interactions. Chatbots are widely utilised in customer service, social media marketing, and client instant messaging.
However, because this is a rudimentary chatbot, we will neither collect nor download any significant datasets. To communicate, these bots may employ Natural Language Processing (NLP) or audio analysis techniques, making them sound more natural. Based on how they're developed, there are two primary sorts of chatbot models: retrieval-based and generation-based models. These intentions may differ from one
chatbot solution to the next depending on the domain in which you are implementing a chatbot solution. AI-Chatbots are widely recommended by entrepreneurs and organizations. Let's take this data science project step by step.
Import and load the data file
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import json
import pickle
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.optimizers import SGD
import random
words=[]
classes = []
documents = []
ignore_words = ['?', '!']
data_file = open('intents.json').read()
intents = json.loads(data_file)
Preprocess data
for intent in intents['intents']:
for pattern in intent['patterns']:
#tokenize each word
w = nltk.word_tokenize(pattern)
words.extend(w)
#add documents in the corpus
documents.append((w, intent['tag']))
if intent['tag'] not in classes:
classes.append(intent['tag'])
Create training and testing data
training = []
output_empty = [0] * len(classes)
for doc in documents:
bag = []
Build the model
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save('chatbot_model.h5', hist)
print("model created"
output_row = list(output_empty)
output_row[classes.index(doc[1])] = 1
training.append([bag, output_row])
random.shuffle(training)
training = np.array(training)
train_x = list(training[:,0])
train_y = list(training[:,1])
print("Training data created")
Predict the response (Graphical User Interface)
import nltk
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from keras.models import load_model
model = load_model('chatbot_model.h5')
import json
import random
intents = json.loads(open('intents.json').read())
words = pickle.load(open('words.pkl','rb'))
def clean_up_sentence(sentence):
sentence_words = nltk.word_tokenize(sentence)
return sentence_words
def bow(sentence, words, show_details=True):
sentence_words = clean_up_sentence(sentence)
bag = [0]*len(words)
for s in sentence_words:
for i,w in enumerate(words):
if w == s:
bag[i] = 1
if show_details:
print ("found in bag: %s" % w)
return(np.array(bag))
def predict_class(sentence, model):
p = bow(sentence, words,show_details=False)
res = model.predict(np.array([p]))[0]
ERROR_THRESHOLD = 0.25
results.sort(key=lambda x: x[1], reverse=True)
return_list = []
for r in results:
return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
return return_list
.def getResponse(ints, intents_json):
tag = ints[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if(i['tag']== tag):
result = random.choice(i['responses'])
break
return result
def chatbot_response(text):
ints = predict_class(text, model)
res = getResponse(ints, intents)
return res
#Creating GUI with tkinter
import tkinter
from tkinter import *
def send():
msg = EntryBox.get("1.0",'end-1c').strip()
EntryBox.delete("0.0",END)
if msg != '':
ChatLog.config(state=NORMAL)
ChatLog.insert(END, "You: " + msg + '\n\n')
ChatLog.config(foreground="#442265", font=("Verdana", 12 ))
res = chatbot_response(msg)
ChatLog.insert(END, "Bot: " + res + '\n\n')
ChatLog.config(state=DISABLED)
ChatLog.yview(END)
base = Tk()
base.title("Hello")
base.geometry("400x500")
base.resizable(width=FALSE, height=FALSE)
#Create Chat window
ChatLog.config(state=DISABLED)
#Bind scrollbar to Chat window
scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
#Create Button to send message
SendButton = Button(base, font=("Verdana",12,'bold'), text="Send", width="12", height=5,
bd=0, bg="#32de97", activebackground="#3c9d9b",fg='#ffffff',
command= send )
#Create the box to enter message
EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial")
#EntryBox.bind("", send)
#Place all components on the screen
scrollbar.place(x=376,y=6, height=386)
ChatLog.place(x=6,y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=90, width=265)
SendButton.place(x=6, y=401, height=90)
base.mainloop()
If you want to learn more about how to do data science projects step by step, visit our website Learnbay: data science course in Chennai.
Keywords | Search Volume | Competition |
data science project | 17,480 | 25 (Low) |
data science projects ideas | 7,690 | 30 (Low) |
data science project for final year | 1,180 | 30(Low) |
Data science project for beginners | 7,500 | 26(Low) |
data science projects step by step | 2,240 | 31 (Low) |
1646796184
Bài viết này dựa trên kinh nghiệm của tôi khi học và vượt qua kỳ thi Chuyên gia bảo mật Kubernetes được chứng nhận. Tôi đã vượt qua kỳ thi trong lần thử đầu tiên vào tháng 9 năm 2021.
Tôi đã vượt qua kỳ thi Nhà phát triển ứng dụng Kubernetes được chứng nhận vào tháng 2 năm 2020, tiếp theo là Quản trị viên Kubernetes được chứng nhận vào tháng 3 năm 2020.
Kỳ thi CKS hoặc Chuyên gia bảo mật Kubernetes được chứng nhận đã được phát hành vào khoảng tháng 11 năm 2020, nhưng tôi không có cơ hội tham gia kỳ thi đó trước tháng 9 năm 2021.
Như một chút thông tin cơ bản, tôi đã làm việc với Kubernetes trong 3 năm qua gần như hàng ngày và kinh nghiệm đó là một lợi thế bổ sung giúp tôi vượt qua CKS.
Trong bài viết này, tôi sẽ chia sẻ một số tài nguyên sẽ giúp bạn học tập và vượt qua kỳ thi, cùng với một bảng đánh giá hữu ích mà bạn có thể sử dụng khi chuẩn bị. Tôi cũng sẽ chia sẻ một số lời khuyên sẽ giúp ích cho bạn trong suốt quá trình.
Kubernetes là hệ thống Điều phối vùng chứa phong phú và phát triển nhất hiện có và nó tiếp tục trở nên tốt hơn.
Nó có một cộng đồng khổng lồ để hỗ trợ và nó luôn xây dựng các tính năng mới và giải quyết các vấn đề. Kubernetes chắc chắn đang phát triển với tốc độ chóng mặt, và nó trở thành một thách thức để theo kịp tốc độ phát triển của nó. Điều này làm cho nó trở thành lựa chọn tốt nhất cho giải pháp điều phối vùng chứa.
Sau đây là một số tài nguyên tuyệt vời có sẵn để vượt qua kỳ thi CKS:
Các khóa học cho KodeKloud và Killer.sh cung cấp các trình mô phỏng kỳ thi thử rất hữu ích trong việc chuẩn bị cho kỳ thi và cung cấp một ý tưởng khá tốt về kỳ thi trông như thế nào. Tôi thực sự khuyên bạn nên đăng ký vào một hoặc cả hai khóa học.
Mua bài kiểm tra từ Linux Foundation mang đến cho bạn 2 lần thử miễn phí trong trình mô phỏng kỳ thi từ killer.sh. Bằng cách đó, nếu bạn đã thành thạo với nội dung của chương trình học, bạn có thể bỏ qua các khóa học và trực tiếp đến với trình mô phỏng kỳ thi được cung cấp kèm theo kỳ thi.
Kỳ thi có giá $ 375 nhưng có các ưu đãi và giao dịch có sẵn, và nếu bạn tìm kiếm chúng, bạn có thể có được mức giá tốt hơn. Thời gian của kỳ thi là 2 giờ và có giá trị trong 2 năm, không giống như CKA và CKAD có giá trị trong 3 năm.
CKS là một kỳ thi dựa trên thành tích, nơi bạn được cung cấp một trình mô phỏng kỳ thi mà bạn phải tìm ra các vấn đề. Bạn chỉ được phép mở một tab ngoài tab kỳ thi.
Vì kỳ thi này yêu cầu bạn viết rất nhiều lệnh, tôi đã sớm nhận ra rằng tôi sẽ phải dựa vào bí danh để giảm số lần nhấn phím nhằm tiết kiệm thời gian.
Tôi đã sử dụng trình soạn thảo vi trong suốt kỳ thi, vì vậy ở đây tôi sẽ chia sẻ một số mẹo hữu ích cho trình soạn thảo này.
vi ~/.vimrc
---
:set number
:set et
:set sw=2 ts=2 sts=2
---
^: Start of word in line
0: Start of line
$: End of line
w: End of word
GG: End of file
vi ~/.bashrc
---
alias k='kubectl'
alias kg='k get'
alias kd='k describe'
alias kl='k logs'
alias ke='k explain'
alias kr='k replace'
alias kc='k create'
alias kgp='k get po'
alias kgn='k get no'
alias kge='k get ev'
alias kex='k exec -it'
alias kgc='k config get-contexts'
alias ksn='k config set-context --current --namespace'
alias kuc='k config use-context'
alias krun='k run'
export do='--dry-run=client -oyaml'
export force='--grace-period=0 --force'
source <(kubectl completion bash)
source <(kubectl completion bash | sed 's/kubectl/k/g' )
complete -F __start_kubectl k
alias krp='k run test --image=busybox --restart=Never'
alias kuc='k config use-context'
---
Lệnh kubectl get
này cung cấp các tên ngắn gọn hấp dẫn để truy cập tài nguyên và tương tự như pvc
đối với persistentstorageclaim
. Những điều này có thể giúp tiết kiệm rất nhiều thao tác gõ phím và thời gian quý báu trong kỳ thi.
pods
replicasets
deployments
services
namespace
networkpolicy
persistentstorage
persistentstorageclaim
serviceaccounts
Lệnh kubectl run
cung cấp một cờ --restart
cho phép bạn tạo các loại đối tượng Kubernetes khác nhau từ Triển khai đến CronJob.
Đoạn mã dưới đây cho thấy các tùy chọn khác nhau có sẵn cho --restart
cờ.
k run:
--restart=Always #Creates a deployment
--restart=Never #Creates a Pod
--restart=OnFailure #Creates a Job
--restart=OnFailure --schedule="*/1 * * * *" #Creates a CronJob
Đôi khi, việc tạo một thông số kỹ thuật từ một nhóm hiện có và thực hiện các thay đổi đối với nó dễ dàng hơn là tạo một nhóm mới từ đầu. Lệnh kubectl get pod
cung cấp cho chúng ta các cờ cần thiết để xuất ra thông số nhóm ở định dạng chúng ta muốn.
kgp <pod-name> -o wide
# Generating YAML Pod spec
kgp <pod-name> -o yaml
kgp <pod-name> -o yaml > <pod-name>.yaml
# Get a pod's YAML spec without cluster specific information
kgp my-pod -o yaml --export > <pod-name>.yaml
Lệnh kubectl run
cung cấp rất nhiều tùy chọn, chẳng hạn như chỉ định các yêu cầu và giới hạn mà một nhóm phải sử dụng hoặc các lệnh mà một vùng chứa sẽ chạy sau khi được tạo.
# Output YAML for a nginx pod running an echo command
krun nginx --image=nginx --restart=Never --dry-run -o yaml -- /bin/sh -c 'echo Hello World!'
# Output YAML for a busybox pod running a sleep command
krun busybox --image=busybox:1.28 --restart=Never --dry-run -o yaml -- /bin/sh -c 'while true; do echo sleep; sleep 10; done'
# Run a pod with set requests and limits
krun nginx --image=nginx --restart=Never --requests='cpu=100m,memory=512Mi' --limits='cpu=300m,memory=1Gi'
# Delete pod without delay
k delete po busybox --grace-period=0 --force
Nhật ký là nguồn thông tin cơ bản khi nói đến gỡ lỗi một ứng dụng. Lệnh kubectl logs
cung cấp chức năng kiểm tra nhật ký của một nhóm nhất định. Bạn có thể sử dụng các lệnh dưới đây để kiểm tra nhật ký của một nhóm nhất định.
kubectl logs deploy/<podname>
kubectl logs deployment/<podname>
#Follow logs
kubectl logs deploy/<podname> --tail 1 --follow
Ngoài việc chỉ xem nhật ký, chúng tôi cũng có thể xuất nhật ký thành tệp để gỡ lỗi thêm khi chia sẻ cùng một tệp với bất kỳ ai.
kubectl logs <podname> --namespace <ns> > /path/to/file.format
Lệnh kubectl create
cho phép chúng tôi tạo Bản đồ cấu hình và Bí mật từ dòng lệnh. Chúng tôi cũng có thể sử dụng tệp YAML để tạo cùng một tài nguyên và bằng cách sử dụng kubectl apply -f <filename>
, chúng tôi có thể áp dụng các lệnh.
kc cm my-cm --from-literal=APP_ENV=dev
kc cm my-cm --from-file=test.txt
kc cm my-cm --from-env-file=config.env
kc secret generic my-secret --from-literal=APP_SECRET=sdcdcsdcsdcsdc
kc secret generic my-secret --from-file=secret.txt
kc secret generic my-secret --from-env-file=secret.env
Gỡ lỗi là một kỹ năng rất quan trọng khi bạn đang đối mặt với các vấn đề và lỗi trong công việc hàng ngày của chúng tôi và khi giải quyết các vấn đề trong kỳ thi CKS.
Ngoài khả năng xuất nhật ký từ vùng chứa, các kubectl exec
lệnh cho phép bạn đăng nhập vào vùng chứa đang chạy và gỡ lỗi các vấn đề. Khi ở bên trong vùng chứa, bạn cũng có thể sử dụng các tiện ích như nc
và nslookup
để chẩn đoán các sự cố liên quan đến mạng.
# Run busybox container
k run busybox --image=busybox:1.28 --rm --restart=Never -it sh
# Connect to a specific container in a Pod
k exec -it busybox -c busybox2 -- /bin/sh
# adding limits and requests in command
kubectl run nginx --image=nginx --restart=Never --requests='cpu=100m,memory=256Mi' --limits='cpu=200m,memory=512Mi'
# Create a Pod with a service
kubectl run nginx --image=nginx --restart=Never --port=80 --expose
# Check port
nc -z -v -w 2 <service-name> <port-name>
# NSLookup
nslookup <service-name>
nslookup 10-32-0-10.default.pod
Lệnh kubectl rollout
cung cấp khả năng kiểm tra trạng thái của các bản cập nhật và nếu được yêu cầu, quay trở lại phiên bản trước đó.
k set image deploy/nginx nginx=nginx:1.17.0 --record
k rollout status deploy/nginx
k rollout history deploy/nginx
# Rollback to previous version
k rollout undo deploy/nginx
# Rollback to revision number
k rollout undo deploy/nginx --to-revision=2
k rollout pause deploy/nginx
k rollout resume deploy/nginx
k rollout restart deploy/nginx
kubectl run nginx-deploy --image=nginx:1.16 --replias=1 --record
Lệnh kubectl scale
cung cấp chức năng mở rộng hoặc thu nhỏ các nhóm trong một triển khai nhất định.
Sử dụng kubectl autoscale
lệnh, chúng tôi có thể xác định số lượng nhóm tối thiểu sẽ chạy cho một triển khai nhất định và số lượng nhóm tối đa mà việc triển khai có thể mở rộng cùng với các tiêu chí mở rộng như tỷ lệ phần trăm CPU.
k scale deploy/nginx --replicas=6
k autoscale deploy/nginx --min=3 --max=9 --cpu-percent=80
Trong một cụm Kubernetes, tất cả các nhóm có thể giao tiếp với tất cả các nhóm theo mặc định, đây có thể là một vấn đề bảo mật trong một số triển khai.
Để giải quyết vấn đề này, Kubernetes đã giới thiệu Chính sách mạng để cho phép hoặc từ chối lưu lượng truy cập đến và đi từ các nhóm dựa trên các nhãn nhóm là một phần của thông số nhóm.
Ví dụ dưới đây từ chối cả lưu lượng vào và ra cho các nhóm đang chạy trong tất cả các không gian tên.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: example
namespace: default
spec:
podSelector: {}
policyTypes:
- Egress
- Ingress
Ví dụ dưới đây từ chối cả lưu lượng vào và ra cho các nhóm đang chạy trong tất cả các không gian tên. Nhưng nó cho phép truy cập vào các dịch vụ phân giải DNS chạy trên cổng 53.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny
namespace: default
spec:
podSelector: {}
policyTypes:
- Egress
- Ingress
egress:
- to:
ports:
- port: 53
protocol: TCP
- port: 53
protocol: UDP
Ví dụ dưới đây từ chối quyền truy cập vào Máy chủ siêu dữ liệu đang chạy trên địa chỉ IP 169.256.169.256
trong Phiên bản AWS EC2.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name:cloud-metadata-deny
namespace: default
spec:
podSelector: {}
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 0.0.0.0/0
except:
- 169.256.169.256/32
Ví dụ dưới đây cho phép Truy cập vào máy chủ siêu dữ liệu đang chạy trên địa chỉ IP 169.256.169.256
trong Phiên bản AWS EC2.
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: cloud-metadata-accessor
namespace: default
spec:
podSelector:
matchLabels:
role: metadata-accessor
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 169.256.169.256/32
Kubesec là một công cụ Phân tích tĩnh để phân tích các tệp YAML để tìm ra các vấn đề với tệp.
kubesec scan pod.yaml
# Using online kubesec API
curl -sSX POST --data-binary @pod.yaml https://v2.kubesec.io/scan
# Running the API locally
kubesec http 8080 &
kubesec scan pod.yaml -o pod_report.json -o json
Trivvy là một công cụ Quét lỗ hổng bảo mật để quét các hình ảnh vùng chứa để tìm các vấn đề bảo mật.
trivy image nginx:1.18.0
trivy image --severity CRITICAL nginx:1.18.0
trivy image --severity CRITICAL, HIGH nginx:1.18.0
trivy image --ignore-unfixed nginx:1.18.0
# Scanning image tarball
docker save nginx:1.18.0 > nginx.tar
trivy image --input archive.tar
# Scan and output results to file
trivy image --output python_alpine.txt python:3.10.0a4-alpine
trivy image --severity HIGH --output /root/python.txt python:3.10.0a4-alpine
# Scan image tarball
trivy image --input alpine.tar --format json --output /root/alpine.json
Tính năng này systemctl
cho thấy các khả năng khởi động, dừng, bật, tắt và liệt kê các dịch vụ đang chạy trên Máy ảo Linux.
Liệt kê các dịch vụ:
systemctl list-units --type service
Dừng phục vụ:
systemctl stop apache2
Tắt dịch vụ:
systemctl disable apache2
Xóa dịch vụ:
apt remove apache2
Kubernetes đã giới thiệu tính năng RuntimeClass trong phiên bản v1.12
để chọn cấu hình thời gian chạy vùng chứa. Cấu hình thời gian chạy của vùng chứa được sử dụng để chạy các vùng chứa bên dưới của một nhóm.
Hầu hết các cụm Kubernetes sử dụng dockershim
làm lớp Thời gian chạy cho các vùng chứa đang chạy, nhưng bạn có thể sử dụng Thời gian chạy vùng chứa khác nhau.
Phiên dockershim
bản Kubernetes đã không còn được dùng nữa v1.20
và sẽ bị xóa trong v1.24
.
Cách tạo một Lớp thời gian chạy:
apiversion: node.k8s.io/v1beta1
kind: RuntimeClass
metadata:
name: gvisor
handler: runsc
Cách sử dụng một lớp thời gian chạy cho bất kỳ nhóm nào đã cho:
apiVersion: v1
kind: Pod
metadata:
labels:
run: nginx
name: nginx
spec:
runtimeClassName: gvisor
containers:
- name: nginx
image: nginx
Trong các chính phủ,
Các lệnh kiểm soát truy cập dựa trên vai trò (RBAC) cung cấp một phương pháp điều chỉnh quyền truy cập vào tài nguyên Kubernetes dựa trên vai trò của từng người dùng hoặc tài khoản dịch vụ. ( Nguồn )
Đây là cách tạo một vai trò:
kubectl create role developer --resource=pods --verb=create,list,get,update,delete --namespace=development
Cách tạo ràng buộc vai trò:
kubectl create rolebinding developer-role-binding --role=developer --user=faizan --namespace=development
Cách xác thực:
kubectl auth can-i update pods --namespace=development --as=faizan
Cách tạo vai trò cụm:
kubectl create clusterrole pvviewer-role --resource=persistentvolumes --verb=list
Và cách tạo liên kết Clusterrole Binding với tài khoản dịch vụ:
kubectl create clusterrolebinding pvviewer-role-binding --clusterrole=pvviewer-role --serviceaccount=default:pvviewer
Bạn sử dụng kubectl drain
lệnh để xóa tất cả khối lượng công việc đang chạy (nhóm) khỏi một Node nhất định.
Bạn sử dụng kubectl cordon
lệnh để buộc một nút để đánh dấu nó là có thể lập lịch.
Bạn sử dụng kubectl uncordon
lệnh để đặt nút là có thể lập lịch, nghĩa là Trình quản lý bộ điều khiển có thể lập lịch các nhóm mới cho nút đã cho.
Cách thoát một nút của tất cả các nhóm:
kubectl drain node-1
Làm thế nào để rút một nút và bỏ qua daemonsets:
kubectl drain node01 --ignore-daemonsets
Làm thế nào để buộc thoát nước:
kubectl drain node02 --ignore-daemonsets --force
Cách đánh dấu một nút là không thể lập lịch để không có nhóm mới nào có thể được lập lịch trên nút này:
kubectl cordon node-1
Đánh dấu một nút có thể lập lịch
kubectl uncordon node-1
Lệnh Kubernetes kubectl get
cung cấp cho người dùng cờ đầu ra -o
hoặc --output
giúp chúng tôi định dạng đầu ra ở dạng JSON, yaml, wide hoặc tùy chỉnh-cột.
Cách xuất nội dung của tất cả các nhóm ở dạng Đối tượng JSON:
kubectl get pods -o json
JSONPath xuất ra một khóa cụ thể từ Đối tượng JSON:
kubectl get pods -o=jsonpath='{@}'
kubectl get pods -o=jsonpath='{.items[0]}'
Được sử dụng khi chúng ta có nhiều đối tượng , .items[*]
ví dụ như nhiều vùng chứa với cấu hình nhóm:
# For list of items use .items[*]
k get pods -o 'jsonpath={.items[*].metadata.labels.version}'
# For single item
k get po busybox -o jsonpath='{.metadata}'
k get po busybox -o jsonpath="{['.metadata.name', '.metadata.namespace']}{'\n'}"
Lệnh trả về IP nội bộ của một Node sử dụng JSONPath:
kubectl get nodes -o=jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
Lệnh kiểm tra sự bình đẳng trên một khóa cụ thể:
kubectl get pod api-stag-765797cf-lrd8q -o=jsonpath='{.spec.volumes[?(@.name=="api-data")].persistentVolumeClaim.claimName}'
kubectl get pod -o=jsonpath='{.items[*].spec.tolerations[?(@.effect=="NoSchedule")].key}'
Các Cột Tùy chỉnh rất hữu ích để xuất ra các trường cụ thể:
kubectl get pods -o='custom-columns=PODS:.metadata.name,Images:.spec.containers[*].image'
Kỳ thi CKS bao gồm các chủ đề liên quan đến bảo mật trong hệ sinh thái Kubernetes. Bảo mật Kubernetes là một chủ đề rộng lớn cần đề cập trong một bài báo, vì vậy bài viết này bao gồm một số chủ đề được đề cập trong kỳ thi.
Trong khi thiết kế hình ảnh vùng chứa để chạy mã của bạn, hãy đặc biệt chú ý đến các biện pháp bảo mật và tăng cường để ngăn chặn các vụ hack và tấn công leo thang đặc quyền. Hãy ghi nhớ những điểm dưới đây khi xây dựng hình ảnh vùng chứa:
alpine:3.13
.USER <username>
để chặn quyền truy cập root.securityContext
sử dụng readOnlyRootFilesystem: true
RUN rm -rf /bin/*
Hướng dẫn RUN
và COPY
tạo ADD
các lớp vùng chứa. Các hướng dẫn khác tạo hình ảnh trung gian tạm thời và không làm tăng kích thước của bản dựng. Các hướng dẫn tạo lớp sẽ bổ sung vào kích thước của hình ảnh kết quả.
Một Dockerfile điển hình trông giống như một tệp được đưa ra bên dưới. Nó thêm một lớp duy nhất bằng cách sử dụng RUN
hướng dẫn.
FROM ubuntu
RUN apt-get update && apt-get install -y golang-go
CMD ["sh"]
Multi-Stage xây dựng đòn bẩy nhiều FROM
câu lệnh trong Dockerfile. Hướng FROM
dẫn đánh dấu một giai đoạn mới trong quá trình xây dựng. Nó kết hợp nhiều FROM
câu lệnh cho phép tận dụng từ bản dựng trước để sao chép có chọn lọc các tệp nhị phân sang giai đoạn xây dựng mới loại bỏ các mã nhị phân không cần thiết. Hình ảnh Docker kết quả có kích thước nhỏ hơn đáng kể với bề mặt tấn công giảm đáng kể.
FROM ubuntu:20.04 AS build
ARG DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y golang-go
COPY app.go .
RUN CGO_ENABLED=0 go build app.go
FROM alpine:3.13
RUN chmod a-w /etc
RUN addgroup -S appgroup && adduser -S appuser -G appgroup -h /home/appuser
RUN rm -rf /bin/*
COPY --from=build /app /home/appuser/
USER appuser
CMD ["/home/appuser/app"]
Các tệp Kiểm soát Truy cập chứa thông tin nhạy cảm về người dùng / nhóm trong Hệ điều hành Linux.
#Stores information about the UID/GID, user shell, and home directory for a user
/etc/passwd
#Stores the user password in a hashed format
/etc/shadow
#Stores information about the group a user belongs
/etc/group
#Stored information about the Sudoers present in the system
/etc/sudoers
Vô hiệu hóa tài khoản người dùng giúp đảm bảo quyền truy cập vào Node bằng cách tắt đăng nhập vào một tài khoản người dùng nhất định.
usermod -s /bin/nologin <username>
Việc vô hiệu hóa root
tài khoản người dùng có ý nghĩa đặc biệt, vì tài khoản gốc có tất cả các khả năng.
usermod -s /bin/nologin root
Đây là cách thêm người dùng với thư mục chính và trình bao:
adduser --home /opt/faizanbashir --shell /bin/bash --uid 2328 --ingroup admin faizanbashir
useradd -d /opt/faizanbashir -s /bin/bash -G admin -u 2328 faizanbashir
Cách xóa tài khoản người dùng:
userdel <username>
Cách xóa một nhóm:
groupdel <groupname>
Cách thêm người dùng vào nhóm:
adduser <username> <groupname>
Cách xóa người dùng khỏi nhóm:
#deluser faizanbashir admin
deluser <username> <groupname>
Cách đặt mật khẩu cho người dùng:
passwd <username>
Cách nâng cao người dùng lên thành sudoer:
vim /etc/sudoers
>>>
faizanbashir ALL=(ALL:ALL) ALL
Cách bật sudo không cần mật khẩu:
vim /etc/sudoers
>>>
faizanbashir ALL=(ALL) NOPASSWD:ALL
visudo
usermod -aG sudo faizanbashir
usermod faizanbashir -G admin
Cấu hình được đưa ra trong /etc/ssh/sshd_config
có thể được tận dụng để bảo mật quyền truy cập SSH vào các nút Linux. Đặt PermitRootLogin
để no
tắt đăng nhập gốc trên một nút.
Để thực thi việc sử dụng khóa để đăng nhập và vô hiệu hóa đăng nhập bằng mật khẩu vào các nút, bạn có thể đặt PasswordAuthentication
thành no
.
vim /etc/ssh/sshd_config
>>
PermitRootLogin no
PasswordAuthentication no
<<
# Restart SSHD Service
systemctl restart sshd
Cách đặt không có đăng nhập cho người dùng root:
usermod -s /bin/nologin root
SSH Sao chép khóa người dùng / SSH không mật khẩu:
ssh-copy-id -i ~/.ssh/id_rsa.pub faizanbashir@node01
ssh faizanbashir@node01
Đây là cách bạn có thể liệt kê tất cả các dịch vụ đang chạy trên máy Ubuntu:
systemctl list-units --type service
systemctl list-units --type service --state running
Cách dừng, tắt và xóa một dịch vụ:
systemctl stop apache2
systemctl disable apache2
apt remove apache2
Trong Linux, mô-đun Kernel là những đoạn mã có thể được tải và dỡ xuống kernel theo yêu cầu. Chúng mở rộng chức năng của hạt nhân mà không cần khởi động lại hệ thống. Một mô-đun có thể được cấu hình dưới dạng tích hợp sẵn hoặc có thể tải được.
Cách liệt kê tất cả các Mô-đun nhân:
lsmod
Cách tải thủ công mô-đun vào Kernel:
modprobe pcspkr
Cách đưa vào danh sách đen một mô-đun: (Tham khảo: CIS Benchmarks -> 3.4 Giao thức mạng không phổ biến)
cat /etc/modprobe.d/blacklist.conf
>>>
blacklist sctp
blacklist dccp
# Shutdown for changes to take effect
shutdown -r now
# Verify
lsmod | grep dccp
Cách kiểm tra các cổng đang mở:
netstat -an | grep -w LISTEN
netstat -natp | grep 9090
nc -zv <hostname|IP> 22
nc -zv <hostname|IP> 10-22
ufw deny 8080
Cách kiểm tra việc sử dụng cổng:
/etc/services | grep -w 53
Đây là tài liệu tham khảo cho danh sách các cổng đang mở .
systemctl status ssh
cat /etc/services | grep ssh
netstat -an | grep 22 | grep -w LISTEN
Tường lửa không phức tạp (UFW) là một công cụ để quản lý các quy tắc tường lửa trong Arch Linux, Debian hoặc Ubuntu. UFW cho phép bạn cho phép và chặn lưu lượng truy cập trên một cổng nhất định và từ một nguồn nhất định.
Đây là cách cài đặt Tường lửa UFW:
apt-get update
apt-get install ufw
systemctl enable ufw
systemctl start ufw
ufw status
ufw status numbered
Cách cho phép tất cả các kết nối đi và đến:
ufw default allow outgoing
ufw default allow incoming
Cách cho phép các quy tắc:
ufw allow 22
ufw allow 1000:2000/tcp
ufw allow from 172.16.238.5 to any port 22 proto tcp
ufw allow from 172.16.238.5 to any port 80 proto tcp
ufw allow from 172.16.100.0/28 to any port 80 proto tcp
Cách từ chối các quy tắc:
ufw deny 8080
Cách bật và kích hoạt Tường lửa:
ufw enable
Cách xóa các quy tắc:
ufw delete deny 8080
ufw delete <rule-line>
Cách đặt lại quy tắc:
ufw reset
Linux Syscalls được sử dụng để thực hiện các yêu cầu từ không gian người dùng vào nhân Linux. Ví dụ: trong khi tạo tệp, không gian người dùng yêu cầu Nhân Linux tạo tệp.
Kernel Space có những thứ sau:
Đây là cách bạn có thể theo dõi các cuộc gọi tổng hợp bằng cách sử dụng strace:
which strace
strace touch /tmp/error.log
Cách lấy PID của một dịch vụ:
pidof sshd
strace -p <pid>
Cách liệt kê tất cả các cuộc gọi tổng hợp được thực hiện trong một hoạt động:
strace -c touch /tmp/error.log
Cách hợp nhất các cuộc gọi hệ thống danh sách: (Đếm và tóm tắt)
strace -cw ls /
Cách theo dõi PID và hợp nhất:
strace -p 3502 -f -cw
AquaSec Tracee được tạo ra bởi Aqua Security, sử dụng eBPF để theo dõi các sự kiện trong vùng chứa. Tracee sử dụng eBPF (Bộ lọc gói Berkeley mở rộng) trong thời gian chạy trực tiếp trong không gian hạt nhân mà không can thiệp vào nguồn hạt nhân hoặc tải bất kỳ mô-đun hạt nhân nào.
/tmp/tracee
--privileged
khả năng:/tmp/tracee
-> Không gian làm việc mặc định/lib/modules
-> Tiêu đề hạt nhân/usr/src
-> Tiêu đề hạt nhânLàm thế nào để Tracee thú vị trong vùng chứa Docker:
docker run --name tracee --rm --privileged --pid=host \
-v /lib/modules/:/lib/modules/:ro -v /usr/src/:/usr/src/ro \
-v /tmp/tracee:/tmp/tracee aquasec/tracee:0.4.0 --trace comm=ls
# List syscalls made by all the new process on the host
docker run --name tracee --rm --privileged --pid=host \
-v /lib/modules/:/lib/modules/:ro -v /usr/src/:/usr/src/ro \
-v /tmp/tracee:/tmp/tracee aquasec/tracee:0.4.0 --trace pid=new
# List syscalls made from any new container
docker run --name tracee --rm --privileged --pid=host \
-v /lib/modules/:/lib/modules/:ro -v /usr/src/:/usr/src/ro \
-v /tmp/tracee:/tmp/tracee aquasec/tracee:0.4.0 --trace container=new
SECCOMP - Chế độ Điện toán Bảo mật - là một tính năng cấp Kernel của Linux mà bạn có thể sử dụng cho các ứng dụng hộp cát để chỉ sử dụng các cuộc gọi hệ thống mà chúng cần.
Cách kiểm tra hỗ trợ cho seccomp:
grep -i seccomp /boot/config-$(uname -r)
Cách kiểm tra để thay đổi thời gian hệ thống:
docker run -it --rm docker/whalesay /bin/sh
# date -s '19 APR 2013 22:00:00'
ps -ef
Cách kiểm tra trạng thái seccomp cho bất kỳ PID nào:
grep -i seccomp /proc/1/status
Chế độ Seccomp:
Cấu hình sau được sử dụng để đưa vào danh sách trắng các cuộc gọi tổng hợp. Hồ sơ danh sách trắng được bảo mật nhưng các cuộc gọi tổng hợp phải được bật có chọn lọc vì nó chặn tất cả các cuộc gọi tổng hợp theo mặc định.
{
"defaultAction": "SCMP_ACT_ERRNO",
"architectures": [
"SCMP_ARCH_X86_64",
"SCMP_ARCH_X86",
"SCMP_ARCH_X32"
],
"syscalls": [
{
"names": [
"<syscall-1>",
"<syscall-2>",
"<syscall-3>"
],
"action": "SCMP_ACT_ALLOW"
}
]
}
Cấu hình sau được sử dụng để danh sách đen các cuộc gọi tổng hợp. Hồ sơ danh sách đen có bề mặt tấn công lớn hơn danh sách trắng.
{
"defaultAction": "SCMP_ACT_ALLOW",
"architectures": [
"SCMP_ARCH_X86_64",
"SCMP_ARCH_X86",
"SCMP_ARCH_X32"
],
"syscalls": [
{
"names": [
"<syscall-1>",
"<syscall-2>",
"<syscall-3>"
],
"action": "SCMP_ACT_ERRNO"
}
]
}
Cấu hình seccomp Docker chặn 60 trong số hơn 300 cuộc gọi tổng hợp trên kiến trúc x86.
Cách sử dụng hồ sơ seccomp với Docker:
docker run -it --rm --security-opt seccomp=/root/custom.json docker/whalesay /bin/sh
Cách cho phép tất cả các cuộc gọi tổng hợp với vùng chứa:
docker run -it --rm --security-opt seccomp=unconfined docker/whalesay /bin/sh
# Verify
grep -i seccomp /proc/1/status
# Output should be:
Seccomp: 0
Cách sử dụng vùng chứa Docker để nhận thông tin liên quan đến thời gian chạy của vùng chứa:
docker run r.j3ss.co/amicontained amicontained
Chế độ điện toán an toàn (SECCOMP) là một tính năng của hạt nhân Linux. Bạn có thể sử dụng nó để hạn chế các tác vụ có sẵn trong vùng chứa. Tài liệu Seccomp
Cách chạy không kiểm soát trong Kubernetes:
kubectl run amicontained --image r.j3ss.co/amicontained amicontained -- amicontained
Kể từ phiên bản v1.20
Kubernetes không triển khai seccomp theo mặc định.
Cấu hình docker Seccomp 'RuntimeDefault' trong Kubernetes:
apiVersion: v1
kind: Pod
metadata:
labels:
run: amicontained
name: amicontained
spec:
securityContext:
seccompProfile:
type: RuntimeDefault
containers:
- args:
- amicontained
image: r.j3ss.co/amicontained
name: amicontained
securityContext:
allowPrivilegeEscalation: false
Vị trí seccomp mặc định trong kubelet
/var/lib/kubelet/seccomp
Cách tạo hồ sơ seccomp trong nút:
mkdir -p /var/lib/kubelet/seccomp/profiles
# Add a profile for audit
vim /var/lib/kubelet/seccomp/profiles/audit.json
>>>
{
defaultAction: "SCMP_ACT_LOG"
}
# Add a profile for violations (Blocks all syscalls by default, will let nothing run)
vim /var/lib/kubelet/seccomp/profiles/violation.json
>>>
{
defaultAction: "SCMP_ACT_ERRNO"
}
Hồ sơ seccomp cục bộ - tệp này phải tồn tại cục bộ trên một nút để có thể hoạt động:
...
securityContext:
seccompProfile:
type: Localhost
localhostProfile: profiles/audit.json
...
Cấu hình trên sẽ cho phép các cuộc gọi tổng hợp được lưu vào một tệp.
grep syscall /var/log/syslog
Cách ánh xạ số syscall với tên syscall:
grep -w 35 /usr/include/asm/unistd_64.h
# OR
grep -w 35 /usr/include/asm-generic/unistd.h
AppArmor là một mô-đun bảo mật Linux được sử dụng để giới hạn một chương trình trong một nhóm tài nguyên giới hạn.
Cách cài đặt AppArmor utils:
apt-get install apparmor-utils
Cách kiểm tra xem AppArmor có đang chạy và được kích hoạt hay không:
systemctl status apparmor
cat /sys/module/apparmor/parameters/enabled
Y
Các cấu hình AppArmor được lưu trữ tại:
cat /etc/apparmor.d/root.add_data.sh
Cách liệt kê hồ sơ AppArmor:
cat /sys/kernel/security/apparmor/profiles
Cách từ chối tất cả các cấu hình ghi tệp:
profile apparmor-deny-write flags=(attach_disconnected) {
file,
# Deny all file writes.
deny /** w,
}
Cách từ chối ghi vào /proc
tệp:
profile apparmor-deny-proc-write flags=(attach_disconnected) {
file,
# Deny all file writes.
deny /proc/* w,
}
Cách từ chối remount root FS:
profile apparmor-deny-remount-root flags=(attach_disconnected) {
# Deny all file writes.
deny mount options=(ro, remount) -> /,
}
Cách kiểm tra trạng thái hồ sơ:
aa-status
Chế độ tải hồ sơ
Enforce
, giám sát và thực thi các quy tắcComplain
, sẽ không thực thi các quy tắc nhưng ghi lại chúng dưới dạng các sự kiệnUnconfined
, sẽ không thực thi hoặc ghi lại các sự kiệnCách kiểm tra xem hồ sơ có hợp lệ không:
apparmor_parser /etc/apparmor.d/root.add_data.sh
Cách tắt cấu hình:
apparmor_parser -R /etc/apparmor.d/root.add_data.sh
ln -s /etc/apparmor.d/root.add_data.sh /etc/apparmor.d/disable/
Cách tạo hồ sơ và trả lời một loạt câu hỏi sau:
aa-genprof /root/add_data.sh
Cách tạo cấu hình cho một lệnh:
aa-genprof curl
Cách tắt cấu hình khỏi nhật ký:
aa-logprof
Để sử dụng AppArmor với Kubernetes, bạn phải đáp ứng các điều kiện tiên quyết sau:
1.4
Cách sử dụng mẫu trong Kubernetes:
apiVersion: v1
kind: Pod
metadata:
name: ubuntu-sleeper
annotations:
container.apparmor.security.beta.kubernetes.io/<container-name>: localhost/<profile-name>
spec:
containers:
- name: ubuntu-sleeper
image: ubuntu
command: ["sh", "-c", "echo 'Sleeping for an hour!' && sleep 1h"]
Lưu ý : Vùng chứa phải chạy trong nút chứa cấu hình AppArmor.
Tính năng khả năng của Linux chia nhỏ các đặc quyền có sẵn cho các quy trình chạy khi root
người dùng thành các nhóm đặc quyền nhỏ hơn. Bằng cách này, một tiến trình đang chạy với root
đặc quyền có thể bị giới hạn để chỉ nhận được những quyền tối thiểu mà nó cần để thực hiện hoạt động của nó.
Docker hỗ trợ các khả năng của Linux như một phần của lệnh chạy Docker: with --cap-add
và --cap-drop
. Theo mặc định, một vùng chứa được khởi động với một số khả năng được cho phép theo mặc định và có thể bị loại bỏ. Các quyền khác có thể được thêm theo cách thủ công.
Cả hai --cap-add
và --cap-drop
hỗ trợ giá trị TẤT CẢ, để cho phép hoặc loại bỏ tất cả các khả năng. Theo mặc định, vùng chứa Docker chạy với 14 khả năng.
CAP_CHOWN
CAP_SYS_TIME
CAP_SYS_BOOT
CAP_NET_ADMIN
Tham khảo tài liệu này để biết danh sách đầy đủ các Khả năng của Linux .
Cách kiểm tra những khả năng mà lệnh cần:
getcap /usr/bin/ping
Cách nhận các khả năng của quy trình:
getpcaps <pid>
Cách thêm khả năng bảo mật:
apiVersion: v1
kind: Pod
metadata:
name: ubuntu-sleeper
spec:
containers:
- name: ubuntu-sleeper
image: ubuntu
command: ["sleep", "1000"]
securityContext:
capabilities:
add: ["SYS_TIME"]
drop: ["CHOWN"]
CKS được đánh giá là một kỳ thi khá khó. Nhưng dựa trên kinh nghiệm của tôi, tôi nghĩ rằng, với thực hành đủ tốt và nếu bạn hiểu các khái niệm mà kỳ thi bao gồm, nó sẽ có thể quản lý được trong vòng hai giờ.
Bạn chắc chắn cần hiểu các khái niệm cơ bản của Kubernetes. Và vì điều kiện tiên quyết đối với CKS là phải vượt qua kỳ thi CKA, bạn nên hiểu rõ về Kubernetes và cách nó hoạt động trước khi thử CKS.
Ngoài ra, để vượt qua CKS, bạn cần hiểu các mối đe dọa và tác động bảo mật được giới thiệu bởi điều phối vùng chứa.
Sự ra đời của kỳ thi CKS là một dấu hiệu cho thấy không nên coi nhẹ an ninh của các thùng chứa. Các cơ chế bảo mật phải luôn có sẵn để ngăn chặn các cuộc tấn công vào các cụm Kubernetes.
Vụ hack tiền điện tử Tesla nhờ vào bảng điều khiển Kubernetes không được bảo vệ, làm sáng tỏ những rủi ro liên quan đến Kubernetes hoặc bất kỳ công cụ điều phối vùng chứa nào khác. Hackerone có một trang tiền thưởng Kubernetes liệt kê các kho mã nguồn được sử dụng trong một cụm Kubernetes tiêu chuẩn.
Thực hành là chìa khóa để bẻ khóa kỳ thi, cá nhân tôi thấy rằng các trình mô phỏng kỳ thi của KodeKloud và Killer.sh vô cùng hữu ích đối với tôi.
Tôi không có nhiều thời gian để chuẩn bị cho kỳ thi CKS như tôi đã có cho kỳ thi CKA, nhưng tôi đang làm việc trên Kubernetes trong công việc hàng ngày của mình nên tôi thực sự cảm thấy thoải mái với nó.
Thực hành là chìa khóa thành công. Chúc bạn may mắn với kỳ thi!
Nguồn: https://www.freecodecamp.org/news/how-to-pass-the-certified-kubernetes-security-specialist-exam/
1646698200
What is face recognition? Or what is recognition? When you look at an apple fruit, your mind immediately tells you that this is an apple fruit. This process, your mind telling you that this is an apple fruit is recognition in simple words. So what is face recognition then? I am sure you have guessed it right. When you look at your friend walking down the street or a picture of him, you recognize that he is your friend Paulo. Interestingly when you look at your friend or a picture of him you look at his face first before looking at anything else. Ever wondered why you do that? This is so that you can recognize him by looking at his face. Well, this is you doing face recognition.
But the real question is how does face recognition works? It is quite simple and intuitive. Take a real life example, when you meet someone first time in your life you don't recognize him, right? While he talks or shakes hands with you, you look at his face, eyes, nose, mouth, color and overall look. This is your mind learning or training for the face recognition of that person by gathering face data. Then he tells you that his name is Paulo. At this point your mind knows that the face data it just learned belongs to Paulo. Now your mind is trained and ready to do face recognition on Paulo's face. Next time when you will see Paulo or his face in a picture you will immediately recognize him. This is how face recognition work. The more you will meet Paulo, the more data your mind will collect about Paulo and especially his face and the better you will become at recognizing him.
Now the next question is how to code face recognition with OpenCV, after all this is the only reason why you are reading this article, right? OK then. You might say that our mind can do these things easily but to actually code them into a computer is difficult? Don't worry, it is not. Thanks to OpenCV, coding face recognition is as easier as it feels. The coding steps for face recognition are same as we discussed it in real life example above.
OpenCV comes equipped with built in face recognizer, all you have to do is feed it the face data. It's that simple and this how it will look once we are done coding it.
OpenCV has three built in face recognizers and thanks to OpenCV's clean coding, you can use any of them by just changing a single line of code. Below are the names of those face recognizers and their OpenCV calls.
cv2.face.createEigenFaceRecognizer()
cv2.face.createFisherFaceRecognizer()
cv2.face.createLBPHFaceRecognizer()
We have got three face recognizers but do you know which one to use and when? Or which one is better? I guess not. So why not go through a brief summary of each, what you say? I am assuming you said yes :) So let's dive into the theory of each.
This algorithm considers the fact that not all parts of a face are equally important and equally useful. When you look at some one you recognize him/her by his distinct features like eyes, nose, cheeks, forehead and how they vary with respect to each other. So you are actually focusing on the areas of maximum change (mathematically speaking, this change is variance) of the face. For example, from eyes to nose there is a significant change and same is the case from nose to mouth. When you look at multiple faces you compare them by looking at these parts of the faces because these parts are the most useful and important components of a face. Important because they catch the maximum change among faces, change the helps you differentiate one face from the other. This is exactly how EigenFaces face recognizer works.
EigenFaces face recognizer looks at all the training images of all the persons as a whole and try to extract the components which are important and useful (the components that catch the maximum variance/change) and discards the rest of the components. This way it not only extracts the important components from the training data but also saves memory by discarding the less important components. These important components it extracts are called principal components. Below is an image showing the principal components extracted from a list of faces.
Principal Components source
You can see that principal components actually represent faces and these faces are called eigen faces and hence the name of the algorithm.
So this is how EigenFaces face recognizer trains itself (by extracting principal components). Remember, it also keeps a record of which principal component belongs to which person. One thing to note in above image is that Eigenfaces algorithm also considers illumination as an important component.
Later during recognition, when you feed a new image to the algorithm, it repeats the same process on that image as well. It extracts the principal component from that new image and compares that component with the list of components it stored during training and finds the component with the best match and returns the person label associated with that best match component.
Easy peasy, right? Next one is easier than this one.
This algorithm is an improved version of EigenFaces face recognizer. Eigenfaces face recognizer looks at all the training faces of all the persons at once and finds principal components from all of them combined. By capturing principal components from all the of them combined you are not focusing on the features that discriminate one person from the other but the features that represent all the persons in the training data as a whole.
This approach has drawbacks, for example, images with sharp changes (like light changes which is not a useful feature at all) may dominate the rest of the images and you may end up with features that are from external source like light and are not useful for discrimination at all. In the end, your principal components will represent light changes and not the actual face features.
Fisherfaces algorithm, instead of extracting useful features that represent all the faces of all the persons, it extracts useful features that discriminate one person from the others. This way features of one person do not dominate over the others and you have the features that discriminate one person from the others.
Below is an image of features extracted using Fisherfaces algorithm.
Fisher Faces source
You can see that features extracted actually represent faces and these faces are called fisher faces and hence the name of the algorithm.
One thing to note here is that even in Fisherfaces algorithm if multiple persons have images with sharp changes due to external sources like light they will dominate over other features and affect recognition accuracy.
Getting bored with this theory? Don't worry, only one face recognizer is left and then we will dive deep into the coding part.
I wrote a detailed explaination on Local Binary Patterns Histograms in my previous article on face detection using local binary patterns histograms. So here I will just give a brief overview of how it works.
We know that Eigenfaces and Fisherfaces are both affected by light and in real life we can't guarantee perfect light conditions. LBPH face recognizer is an improvement to overcome this drawback.
Idea is to not look at the image as a whole instead find the local features of an image. LBPH alogrithm try to find the local structure of an image and it does that by comparing each pixel with its neighboring pixels.
Take a 3x3 window and move it one image, at each move (each local part of an image), compare the pixel at the center with its neighbor pixels. The neighbors with intensity value less than or equal to center pixel are denoted by 1 and others by 0. Then you read these 0/1 values under 3x3 window in a clockwise order and you will have a binary pattern like 11100011 and this pattern is local to some area of the image. You do this on whole image and you will have a list of local binary patterns.
LBP Labeling
Now you get why this algorithm has Local Binary Patterns in its name? Because you get a list of local binary patterns. Now you may be wondering, what about the histogram part of the LBPH? Well after you get a list of local binary patterns, you convert each binary pattern into a decimal number (as shown in above image) and then you make a histogram of all of those values. A sample histogram looks like this.
Sample Histogram
I guess this answers the question about histogram part. So in the end you will have one histogram for each face image in the training data set. That means if there were 100 images in training data set then LBPH will extract 100 histograms after training and store them for later recognition. Remember, algorithm also keeps track of which histogram belongs to which person.
Later during recognition, when you will feed a new image to the recognizer for recognition it will generate a histogram for that new image, compare that histogram with the histograms it already has, find the best match histogram and return the person label associated with that best match histogram.
Below is a list of faces and their respective local binary patterns images. You can see that the LBP images are not affected by changes in light conditions.
LBP Faces source
The theory part is over and now comes the coding part! Ready to dive into coding? Let's get into it then.
Coding Face Recognition with OpenCV
The Face Recognition process in this tutorial is divided into three steps.
[There should be a visualization diagram for above steps here]
To detect faces, I will use the code from my previous article on face detection. So if you have not read it, I encourage you to do so to understand how face detection works and its Python coding.
Before starting the actual coding we need to import the required modules for coding. So let's import them first.
#import OpenCV module
import cv2
#import os module for reading training data directories and paths
import os
#import numpy to convert python lists to numpy arrays as
#it is needed by OpenCV face recognizers
import numpy as np
#matplotlib for display our images
import matplotlib.pyplot as plt
%matplotlib inline
The more images used in training the better. Normally a lot of images are used for training a face recognizer so that it can learn different looks of the same person, for example with glasses, without glasses, laughing, sad, happy, crying, with beard, without beard etc. To keep our tutorial simple we are going to use only 12 images for each person.
So our training data consists of total 2 persons with 12 images of each person. All training data is inside training-data
folder. training-data
folder contains one folder for each person and each folder is named with format sLabel (e.g. s1, s2)
where label is actually the integer label assigned to that person. For example folder named s1 means that this folder contains images for person 1. The directory structure tree for training data is as follows:
training-data
|-------------- s1
| |-- 1.jpg
| |-- ...
| |-- 12.jpg
|-------------- s2
| |-- 1.jpg
| |-- ...
| |-- 12.jpg
The test-data
folder contains images that we will use to test our face recognizer after it has been successfully trained.
As OpenCV face recognizer accepts labels as integers so we need to define a mapping between integer labels and persons actual names so below I am defining a mapping of persons integer labels and their respective names.
Note: As we have not assigned label 0
to any person so the mapping for label 0 is empty.
#there is no label 0 in our training data so subject name for index/label 0 is empty
subjects = ["", "Tom Cruise", "Shahrukh Khan"]
You may be wondering why data preparation, right? Well, OpenCV face recognizer accepts data in a specific format. It accepts two vectors, one vector is of faces of all the persons and the second vector is of integer labels for each face so that when processing a face the face recognizer knows which person that particular face belongs too.
For example, if we had 2 persons and 2 images for each person.
PERSON-1 PERSON-2
img1 img1
img2 img2
Then the prepare data step will produce following face and label vectors.
FACES LABELS
person1_img1_face 1
person1_img2_face 1
person2_img1_face 2
person2_img2_face 2
Preparing data step can be further divided into following sub-steps.
s1, s2
.sLabel
where Label
is an integer representing the label we have assigned to that subject. So for example, folder name s1
means that the subject has label 1, s2 means subject label is 2 and so on. The label extracted in this step is assigned to each face detected in the next step.[There should be a visualization for above steps here]
Did you read my last article on face detection? No? Then you better do so right now because to detect faces, I am going to use the code from my previous article on face detection. So if you have not read it, I encourage you to do so to understand how face detection works and its coding. Below is the same code.
#function to detect face using OpenCV
def detect_face(img):
#convert the test image to gray image as opencv face detector expects gray images
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#load OpenCV face detector, I am using LBP which is fast
#there is also a more accurate but slow Haar classifier
face_cascade = cv2.CascadeClassifier('opencv-files/lbpcascade_frontalface.xml')
#let's detect multiscale (some images may be closer to camera than others) images
#result is a list of faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
#if no faces are detected then return original img
if (len(faces) == 0):
return None, None
#under the assumption that there will be only one face,
#extract the face area
(x, y, w, h) = faces[0]
#return only the face part of the image
return gray[y:y+w, x:x+h], faces[0]
I am using OpenCV's LBP face detector. On line 4, I convert the image to grayscale because most operations in OpenCV are performed in gray scale, then on line 8 I load LBP face detector using cv2.CascadeClassifier
class. After that on line 12 I use cv2.CascadeClassifier
class' detectMultiScale
method to detect all the faces in the image. on line 20, from detected faces I only pick the first face because in one image there will be only one face (under the assumption that there will be only one prominent face). As faces returned by detectMultiScale
method are actually rectangles (x, y, width, height) and not actual faces images so we have to extract face image area from the main image. So on line 23 I extract face area from gray image and return both the face image area and face rectangle.
Now you have got a face detector and you know the 4 steps to prepare the data, so are you ready to code the prepare data step? Yes? So let's do it.
#this function will read all persons' training images, detect face from each image
#and will return two lists of exactly same size, one list
# of faces and another list of labels for each face
def prepare_training_data(data_folder_path):
#------STEP-1--------
#get the directories (one directory for each subject) in data folder
dirs = os.listdir(data_folder_path)
#list to hold all subject faces
faces = []
#list to hold labels for all subjects
labels = []
#let's go through each directory and read images within it
for dir_name in dirs:
#our subject directories start with letter 's' so
#ignore any non-relevant directories if any
if not dir_name.startswith("s"):
continue;
#------STEP-2--------
#extract label number of subject from dir_name
#format of dir name = slabel
#, so removing letter 's' from dir_name will give us label
label = int(dir_name.replace("s", ""))
#build path of directory containin images for current subject subject
#sample subject_dir_path = "training-data/s1"
subject_dir_path = data_folder_path + "/" + dir_name
#get the images names that are inside the given subject directory
subject_images_names = os.listdir(subject_dir_path)
#------STEP-3--------
#go through each image name, read image,
#detect face and add face to list of faces
for image_name in subject_images_names:
#ignore system files like .DS_Store
if image_name.startswith("."):
continue;
#build image path
#sample image path = training-data/s1/1.pgm
image_path = subject_dir_path + "/" + image_name
#read image
image = cv2.imread(image_path)
#display an image window to show the image
cv2.imshow("Training on image...", image)
cv2.waitKey(100)
#detect face
face, rect = detect_face(image)
#------STEP-4--------
#for the purpose of this tutorial
#we will ignore faces that are not detected
if face is not None:
#add face to list of faces
faces.append(face)
#add label for this face
labels.append(label)
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.destroyAllWindows()
return faces, labels
I have defined a function that takes the path, where training subjects' folders are stored, as parameter. This function follows the same 4 prepare data substeps mentioned above.
(step-1) On line 8 I am using os.listdir
method to read names of all folders stored on path passed to function as parameter. On line 10-13 I am defining labels and faces vectors.
(step-2) After that I traverse through all subjects' folder names and from each subject's folder name on line 27 I am extracting the label information. As folder names follow the sLabel
naming convention so removing the letter s
from folder name will give us the label assigned to that subject.
(step-3) On line 34, I read all the images names of of the current subject being traversed and on line 39-66 I traverse those images one by one. On line 53-54 I am using OpenCV's imshow(window_title, image)
along with OpenCV's waitKey(interval)
method to display the current image being traveresed. The waitKey(interval)
method pauses the code flow for the given interval (milliseconds), I am using it with 100ms interval so that we can view the image window for 100ms. On line 57, I detect face from the current image being traversed.
(step-4) On line 62-66, I add the detected face and label to their respective vectors.
But a function can't do anything unless we call it on some data that it has to prepare, right? Don't worry, I have got data of two beautiful and famous celebrities. I am sure you will recognize them!
Let's call this function on images of these beautiful celebrities to prepare data for training of our Face Recognizer. Below is a simple code to do that.
#let's first prepare our training data
#data will be in two lists of same size
#one list will contain all the faces
#and other list will contain respective labels for each face
print("Preparing data...")
faces, labels = prepare_training_data("training-data")
print("Data prepared")
#print total faces and labels
print("Total faces: ", len(faces))
print("Total labels: ", len(labels))
Preparing data...
Data prepared
Total faces: 23
Total labels: 23
This was probably the boring part, right? Don't worry, the fun stuff is coming up next. It's time to train our own face recognizer so that once trained it can recognize new faces of the persons it was trained on. Read? Ok then let's train our face recognizer.
As we know, OpenCV comes equipped with three face recognizers.
cv2.face.createEigenFaceRecognizer()
cv2.face.createFisherFaceRecognizer()
cv2.face.LBPHFisherFaceRecognizer()
I am going to use LBPH face recognizer but you can use any face recognizer of your choice. No matter which of the OpenCV's face recognizer you use the code will remain the same. You just have to change one line, the face recognizer initialization line given below.
#create our LBPH face recognizer
face_recognizer = cv2.face.createLBPHFaceRecognizer()
#or use EigenFaceRecognizer by replacing above line with
#face_recognizer = cv2.face.createEigenFaceRecognizer()
#or use FisherFaceRecognizer by replacing above line with
#face_recognizer = cv2.face.createFisherFaceRecognizer()
Now that we have initialized our face recognizer and we also have prepared our training data, it's time to train the face recognizer. We will do that by calling the train(faces-vector, labels-vector)
method of face recognizer.
#train our face recognizer of our training faces
face_recognizer.train(faces, np.array(labels))
Did you notice that instead of passing labels
vector directly to face recognizer I am first converting it to numpy array? This is because OpenCV expects labels vector to be a numpy
array.
Still not satisfied? Want to see some action? Next step is the real action, I promise!
Now comes my favorite part, the prediction part. This is where we actually get to see if our algorithm is actually recognizing our trained subjects's faces or not. We will take two test images of our celeberities, detect faces from each of them and then pass those faces to our trained face recognizer to see if it recognizes them.
Below are some utility functions that we will use for drawing bounding box (rectangle) around face and putting celeberity name near the face bounding box.
#function to draw rectangle on image
#according to given (x, y) coordinates and
#given width and heigh
def draw_rectangle(img, rect):
(x, y, w, h) = rect
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
#function to draw text on give image starting from
#passed (x, y) coordinates.
def draw_text(img, text, x, y):
cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
First function draw_rectangle
draws a rectangle on image based on passed rectangle coordinates. It uses OpenCV's built in function cv2.rectangle(img, topLeftPoint, bottomRightPoint, rgbColor, lineWidth)
to draw rectangle. We will use it to draw a rectangle around the face detected in test image.
Second function draw_text
uses OpenCV's built in function cv2.putText(img, text, startPoint, font, fontSize, rgbColor, lineWidth)
to draw text on image.
Now that we have the drawing functions, we just need to call the face recognizer's predict(face)
method to test our face recognizer on test images. Following function does the prediction for us.
#this function recognizes the person in image passed
#and draws a rectangle around detected face with name of the
#subject
def predict(test_img):
#make a copy of the image as we don't want to chang original image
img = test_img.copy()
#detect face from the image
face, rect = detect_face(img)
#predict the image using our face recognizer
label= face_recognizer.predict(face)
#get name of respective label returned by face recognizer
label_text = subjects[label]
#draw a rectangle around face detected
draw_rectangle(img, rect)
#draw name of predicted person
draw_text(img, label_text, rect[0], rect[1]-5)
return img
predict(face)
method. This method will return a lableNow that we have the prediction function well defined, next step is to actually call this function on our test images and display those test images to see if our face recognizer correctly recognized them. So let's do it. This is what we have been waiting for.
print("Predicting images...")
#load test images
test_img1 = cv2.imread("test-data/test1.jpg")
test_img2 = cv2.imread("test-data/test2.jpg")
#perform a prediction
predicted_img1 = predict(test_img1)
predicted_img2 = predict(test_img2)
print("Prediction complete")
#create a figure of 2 plots (one for each test image)
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
#display test image1 result
ax1.imshow(cv2.cvtColor(predicted_img1, cv2.COLOR_BGR2RGB))
#display test image2 result
ax2.imshow(cv2.cvtColor(predicted_img2, cv2.COLOR_BGR2RGB))
#display both images
cv2.imshow("Tom cruise test", predicted_img1)
cv2.imshow("Shahrukh Khan test", predicted_img2)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.destroyAllWindows()
Predicting images...
Prediction complete
wohooo! Is'nt it beautiful? Indeed, it is!
Face Recognition is a fascinating idea to work on and OpenCV has made it extremely simple and easy for us to code it. It just takes a few lines of code to have a fully working face recognition application and we can switch between all three face recognizers with a single line of code change. It's that simple.
Although EigenFaces, FisherFaces and LBPH face recognizers are good but there are even better ways to perform face recognition like using Histogram of Oriented Gradients (HOGs) and Neural Networks. So the more advanced face recognition algorithms are now a days implemented using a combination of OpenCV and Machine learning. I have plans to write some articles on those more advanced methods as well, so stay tuned!
Download Details:
Author: informramiz
Source Code: https://github.com/informramiz/opencv-face-recognition-python
License: MIT License