Initial commit

This commit is contained in:
VladislavOstapov 2022-11-22 20:51:20 +03:00
parent fbe67387fb
commit 5408430646
10 changed files with 4604 additions and 0 deletions

162
lab2_1/lab2_1.py Normal file
View File

@ -0,0 +1,162 @@
import os
import sys
import cv2
import numpy as np
from matplotlib import pyplot as plt
def menu():
print("Выберите пункт меню:\n1.Linear filter\n2.Blur\n3.Median blur\n4.GaussianBlur\n5.Erode")
print("6.Dilate\n7.MORPH_OPERATIONS\n8.Sobel\n9.Laplacian\n10.Canny\n11.CalcHist\n12.EqualizeHist")
print("13.Save\n14.Add Figure\n15.Del Figure\n16.Exit")
def main():
image1 = cv2.imread("D:\\MACH\\LAB_2\\image0.jpg")
image2 = image1.copy()
im = image1.copy()
while True:
menu()
try:
s = int(input())
if s == 1:
image2 = image1.copy()
kernel = np.array([[-0.1, 0.2, -0.1], [0.2, 3.0, 0.2], [-0.1, 0.2, -0.1]])
image2 = cv2.filter2D(image2, -1, kernel)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 2:
image2 = image1.copy()
image2 = cv2.blur(image2, (5, 5))
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 3:
image2 = image1.copy()
image2 = cv2.medianBlur(image2, 5)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 4:
image2 = image1.copy()
image2 = cv2.GaussianBlur(image2, (9, 9), cv2.BORDER_DEFAULT)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 5:
image2 = image1.copy()
image2 = cv2.erode(image2, np.ones((11, 11)))
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 6:
image2 = image1.copy()
image2 = cv2.dilate(image2, np.ones((11, 11)))
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 7:
image2 = image1.copy()
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
cv2.imshow("Image_load", image1)
kernel = np.ones((6, 6), np.uint8)
image3 = cv2.morphologyEx(image3, cv2.MORPH_OPEN, kernel, iterations=1)
cv2.imshow("MORPH_OPEN", image3)
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
image3 = cv2.morphologyEx(image3, cv2.MORPH_CLOSE, kernel, iterations=1)
cv2.imshow("MORPH_CLOSE", image3)
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
image3 = cv2.morphologyEx(image3, cv2.MORPH_GRADIENT, kernel, iterations=1)
cv2.imshow("MORPH_GRADIENT", image3)
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
image3 = cv2.morphologyEx(image3, cv2.MORPH_TOPHAT, kernel, iterations=1)
cv2.imshow("MORPH_TOPHAT", image3)
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
image3 = cv2.morphologyEx(image3, cv2.MORPH_BLACKHAT, kernel, iterations=1)
cv2.imshow("MORPH_BLACKHAT", image3)
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
cv2.waitKey(0)
if s == 8:
image2 = image1.copy()
image3 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
image3 = cv2.GaussianBlur(image3, (3, 3), 0)
im3 = cv2.Sobel(image3, cv2.CV_64F, 1, 0, ksize=5)
im4 = cv2.Sobel(image3, cv2.CV_64F, 0, 1, ksize=5)
im5 = cv2.Sobel(image3, cv2.CV_8UC1, 0, 1, ksize=5)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image_X", im3) # x
cv2.imshow("Result_Image_Y", im4) # y
cv2.imshow("Result_Gradient", im5) # gradient
cv2.waitKey(0)
if s == 9:
image2 = image1.copy()
image3 = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)
image3 = cv2.GaussianBlur(image3, (3, 3), 0)
im3 = cv2.Laplacian(image3, cv2.CV_64F)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", im3) # x
cv2.waitKey(0)
if s == 10:
image2 = image1.copy()
image3 = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)
image3 = cv2.blur(image2, (5, 5))
image3 = cv2.Canny(image3, 100, 100)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image3) # x
cv2.waitKey(0)
if s == 11:
image2 = image1.copy()
color = ('b', 'g', 'r')
cv2.imshow("Image_load", image1)
for i, col in enumerate(color):
histr = cv2.calcHist([image2], [i], None, [256], [0, 256])
plt.plot(histr, color=col)
plt.xlim([0, 256])
plt.show()
plt.close()
cv2.waitKey(0)
if s == 12:
image2 = image1.copy()
image2 = cv2.cvtColor(image2, cv2.COLOR_RGB2GRAY)
image2 = cv2.equalizeHist(image2)
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.waitKey(0)
if s == 13:
cv2.imshow("Image_load", image1)
cv2.imshow("Result_Image", image2)
cv2.imwrite("D:\\im1.jpg", image1)
cv2.imwrite("D:\\im2.jpg", image2)
cv2.waitKey(0)
if s == 14:
image2 = image1.copy()
cv2.imshow("Image_load", image1)
image2 = cv2.line(image2, (15, 15), (270, 270), (76, 187, 23), 10) # линия
image2 = cv2.rectangle(image2, (20, 20), (100, 100), (0, 0, 255), 10) # нарисуем четырехугольник
image2 = cv2.circle(image2, (100, 100), 40, (0, 255, 0), 10) # нарисуем круг
cv2.imshow("Result_Image", image2)
image1 = image2
cv2.waitKey(0)
if s == 15:
cv2.imwrite("1.jpg", im)
cv2.imwrite("2.jpg", image1)
img = cv2.imread("1.jpg")
mask = cv2.imread("2.jpg", 0)
res = cv2.bitwise_and(img, img, mask=mask)
image2 = res.copy()
image1 = res.copy()
cv2.imshow("Result_Image", res)
cv2.waitKey(0)
os.remove("1.jpg")
os.remove("2.jpg")
if s == 16:
cv2.destroyAllWindows()
sys.exit(0)
except ValueError:
print("Неверный пункт меню!!!! Выберите другое!")
if __name__ == "__main__":
main()

21
lab2_2/Operate.txt Normal file
View File

@ -0,0 +1,21 @@
1.Image
2.Linear filter
3.Blur
4.Median blur
5.GaussianBlur
6.Erode
7.Dilate
8.1.MORPH_MORPH_OPEN
8.2.MORPH_MORPH_CLOSE
8.3.MORPH_MORPH_GRADIENT
8.4.MORPH_MORPH_TOPHAT
8.5.MORPH_MORPH_BLACKHAT
9.Sobel_X
10.Sobel_Y
11.Sobel_Gradient
12.Laplacian
13.Canny
14.CalcHist
15.EqualizeHist
16.Add Figure
17.Del Figure

271
lab2_2/lab2_2.py Normal file
View File

@ -0,0 +1,271 @@
import sys
import cv2
import numpy
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QVBoxLayout, QHBoxLayout, QPushButton, QFileDialog,QComboBox,QMessageBox
from PyQt5.QtCore import Qt
from matplotlib import pyplot as plt
class Example(QWidget):
def __init__(self):
super().__init__()
self.image = None
self.label = QLabel()
self.initUI()
def initUI(self):
self.label.setText('OpenCV Image')
self.label.setAlignment(Qt.AlignCenter)
btn_open = QPushButton('Открыть изображение')
btn_open.clicked.connect(self.openImage)
btn_procesar = QPushButton('Сохранить изображение')
btn_procesar.clicked.connect(self.saveImage)
f=open("Operate.txt","r")
attr=f.read().splitlines()
f.close()
self.oper=QComboBox()
self.oper.addItems(attr)
self.oper.currentIndexChanged.connect(self.combobox)
top_bar = QHBoxLayout()
top_bar.addWidget(btn_open)
top_bar.addWidget(btn_procesar)
top_bar.addWidget(self.oper)
root = QVBoxLayout(self)
root.addLayout(top_bar)
root.addWidget(self.label)
self.resize(540, 574)
self.setWindowTitle('ST_2_2')
self.show()
def openImage(self):
self.filename, _ = QFileDialog.getOpenFileName(None, 'Buscar Imagen', '.', 'Image Files (*.png *.jpg *.jpeg *.bmp)')
if self.filename:
with open(self.filename, "rb") as file:
data = numpy.array(bytearray(file.read()))
self.image = cv2.imdecode(data, cv2.IMREAD_UNCHANGED)
self.mostrarImagen(self.image)
self.image2=self.image
def saveImage(self):
filename = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","Image Files (*.jpg)")
img=self.image2
cv2.imwrite(filename[0],img)
def mostrarImagen(self,s):
size = s.shape
step = s.size / size[0]
qformat = QImage.Format_Indexed8
if len(size) == 3:
if size[2] == 4:
qformat = QImage.Format_RGBA8888
else:
qformat = QImage.Format_RGB888
img = QImage(s, size[1], size[0], step, qformat)
img = img.rgbSwapped()
self.label.setPixmap(QPixmap.fromImage(img))
self.resize(self.label.pixmap().size())
def combobox(self, index):
if index==0:
self.i0()
if index==1:
self.i1()
if index==2:
self.i2()
if index==3:
self.i3()
if index==4:
self.i4()
if index==5:
self.i5()
if index==6:
self.i6()
if index==7:
self.i7()
if index==8:
self.i8()
if index==9:
self.i9()
if index==10:
self.i10()
if index==11:
self.i11()
if index==12:
self.i12()
if index==13:
self.i13()
if index==14:
self.i14()
if index==15:
self.i15()
if index==16:
self.i16()
if index==17:
self.i17()
if index==18:
self.i18()
if index==19:
self.i19()
if index==20:
self.i20()
def i0(self):
self.image2=self.image
self.mostrarImagen(self.image)
def i1(self):
self.image2=self.image
kernel = numpy.array([[-0.1,0.2,-0.1],[0.2,3.0,0.2],[-0.1,0.2,-0.1]])
self.image2=cv2.filter2D(self.image2,-1,kernel)
self.mostrarImagen(self.image2)
def i2(self):
self.image2=self.image
self.image2 = cv2.blur(self.image2,(5,5))
self.mostrarImagen(self.image2)
def i3(self):
self.image2=self.image
self.image2 = cv2.medianBlur(self.image2,5)
self.mostrarImagen(self.image2)
def i4(self):
self.image2=self.image
self.image2 = cv2.GaussianBlur(self.image2, (9,9),cv2.BORDER_DEFAULT)
self.mostrarImagen(self.image2)
def i5(self):
self.image2=self.image
self.image2 = cv2.erode(self.image2, numpy.ones((11, 11)))
self.mostrarImagen(self.image2)
def i6(self):
self.image2=self.image
self.image2 = cv2.dilate(self.image2, numpy.ones((11, 11)))
self.mostrarImagen(self.image2)
def i7(self):
self.image2=self.image
kernel = numpy.ones((6,6),numpy.uint8)
self.image2=cv2.morphologyEx(self.image2, cv2.MORPH_OPEN, kernel,iterations = 1)
self.mostrarImagen(self.image2)
def i8(self):
self.image2=self.image
kernel = numpy.ones((6,6),numpy.uint8)
self.image2=cv2.morphologyEx(self.image2, cv2.MORPH_CLOSE, kernel,iterations = 1)
self.mostrarImagen(self.image2)
def i9(self):
self.image2=self.image
kernel = numpy.ones((6,6),numpy.uint8)
self.image2=cv2.morphologyEx(self.image2, cv2.MORPH_GRADIENT, kernel,iterations = 1)
self.mostrarImagen(self.image2)
def i10(self):
self.image2=self.image
kernel = numpy.ones((6,6),numpy.uint8)
self.image2=cv2.morphologyEx(self.image2, cv2.MORPH_TOPHAT, kernel,iterations = 1)
self.mostrarImagen(self.image2)
def i11(self):
self.image2=self.image
kernel = numpy.ones((6,6),numpy.uint8)
self.image2=cv2.morphologyEx(self.image2, cv2.MORPH_BLACKHAT, kernel,iterations = 1)
self.mostrarImagen(self.image2)
def i12(self):
self.image2=self.image
self.image2 = cv2.cvtColor(self.image2,cv2.COLOR_BGR2GRAY)
self.image2 = cv2.GaussianBlur(self.image2,(3,3),0)
self.image2 = cv2.Sobel(self.image2,cv2.CV_64F,1,0,ksize=5)
self.mostrarImagen(self.image2)
def i13(self):
self.image2=self.image
self.image2 = cv2.cvtColor(self.image2,cv2.COLOR_BGR2GRAY)
self.image2 = cv2.GaussianBlur(self.image2,(3,3),0)
self.image2 = cv2.Sobel(self.image2,cv2.CV_64F,0,1,ksize=5)
self.mostrarImagen(self.image2)
def i14(self):
self.image2=self.image
self.image2 = cv2.cvtColor(self.image2,cv2.COLOR_BGR2GRAY)
self.image2 = cv2.GaussianBlur(self.image2,(3,3),0)
self.image2 = cv2.Sobel(self.image2,cv2.CV_8UC1,0,1,ksize=5)
self.mostrarImagen(self.image2)
def i15(self):
self.image2=self.image
self.image2 = cv2.cvtColor(self.image2,cv2.COLOR_RGB2GRAY)
self.image2 = cv2.GaussianBlur(self.image2,(3,3),0)
self.image2 = cv2.Laplacian(self.image2,cv2.CV_64F)
self.mostrarImagen(self.image2)
def i16(self):
self.image2=self.image
self.image2 = cv2.cvtColor(self.image2,cv2.COLOR_RGB2GRAY)
self.image2 = cv2.blur(self.image2,(5,5))
self.image2 = cv2.Canny(self.image2, 100, 100)
self.mostrarImagen(self.image2)
def i17(self):
self.image2=self.image
color = ('b','g','r')
for i,col in enumerate(color):
histr = cv2.calcHist([self.image2],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
def i18(self):
self.image2=self.image
self.image2 = cv2.cvtColor(self.image2,cv2.COLOR_RGB2GRAY)
self.image2 = cv2.equalizeHist(self.image2)
self.mostrarImagen(self.image2)
def i19(self):
self.image2=self.image
self.image2 = cv2.line(self.image2,(15,15),(270,270),(76,187,23),10)#линия
self.image2 = cv2.rectangle(self.image2,(20,20),(100,100),(0,0,255),10)#нарисуем четырехугольник
self.image2 = cv2.circle(self.image2,(100,100),40,(0,255,0),10)#нарисуем круг
self.image=self.image2
self.mostrarImagen(self.image2)
def i20(self):
if self.filename:
with open(self.filename, "rb") as file:
data = numpy.array(bytearray(file.read()))
self.image = cv2.imdecode(data, cv2.IMREAD_UNCHANGED)
self.mostrarImagen(self.image)
self.mostrarImagen(self.image)
self.image2=self.image
def closeEvent(self, event):
close = QMessageBox.question(self,"Выход","Вы хотите завершить работу?",QMessageBox.Yes | QMessageBox.No)
if close == QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Example()
sys.exit(app.exec_())

81
lab4/1.yml Normal file
View File

@ -0,0 +1,81 @@
%YAML:1.0
---
opencv_ml_svm:
format: 3
svmType: C_SVC
kernel:
type: RBF
gamma: 1.
C: 1.
term_criteria: { epsilon:1.1920928955078125e-07, iterations:1000 }
var_count: 1
class_count: 2
class_labels: !!opencv-matrix
rows: 2
cols: 1
dt: i
data: [ -1, 1 ]
sv_total: 50
support_vectors:
- [ 0. ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 0. ]
- [ 2.80259693e-45 ]
- [ 0. ]
- [ 2.80259693e-45 ]
- [ 2.80259693e-45 ]
- [ 2.80259693e-45 ]
- [ 2.80259693e-45 ]
- [ 4.20389539e-45 ]
- [ 2.80259693e-45 ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 2.80259693e-45 ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 2.80259693e-45 ]
- [ 2.80259693e-45 ]
- [ 1.40129846e-45 ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 0. ]
- [ 2.80259693e-45 ]
- [ 0. ]
- [ 1.40129846e-45 ]
- [ 2.80259693e-45 ]
- [ 1.40129846e-45 ]
- [ 0. ]
decision_functions:
-
sv_count: 50
rho: 0.
alpha: [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., -1., -1., -1.,
-1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1., -1.,
-1., -1., -1., -1., -1., -1., -1., -1., -1., -1. ]
index: [ 12, 15, 2, 16, 4, 5, 21, 24, 8, 31, 10, 11, 23, 13, 14,
29, 30, 32, 33, 40, 42, 44, 46, 47, 48, 19, 26, 27, 28, 1,
3, 25, 0, 7, 34, 35, 36, 37, 38, 39, 9, 41, 6, 43, 17, 45,
18, 20, 22, 49 ]

214
lab4/lab4.py Normal file
View File

@ -0,0 +1,214 @@
#import numpy as np
#import cv2
#img = cv2.imread("D:\MACH\LAB_4\crocodile\image_0001.jpg")
#gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#sift = cv2.SIFT_create()
#kp = sift.detect(gray,None)
#img=cv2.drawKeypoints(gray,kp,img)
#cv2.imshow("R",img)
#cv2.waitKey(0)
#cv2.destroyAllWindows()
import sys
import cv2
import numpy as np
import random
import math
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import (QWidget, QApplication, QLabel, QVBoxLayout, QHBoxLayout, QPushButton,
QFileDialog,QComboBox,QMessageBox,QTextBrowser)
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.image = None
self.textbrowser = QTextBrowser()
self.initUI()
def initUI(self):
self.btn_open = QPushButton('Изображения folder1')
self.btn_open.clicked.connect(self.openImages1)
self.btn_open1 = QPushButton('Изображения folder2')
self.btn_open1.clicked.connect(self.openImages2)
self.btn_ = QPushButton('Обучить и создать матрицы')
self.btn_.clicked.connect(self.matrix_and_train)
self.btn1 = QPushButton('Детектировать тестовые изображения')
self.btn1.clicked.connect(self.detect_image)
self.btn2 = QPushButton('Сформировать лес и натренировать полученную модель')
self.btn2.clicked.connect(self.form_les_and_train)
self.btn_.setVisible(False)
self.btn1.setVisible(False)
self.btn2.setVisible(False)
top_bar = QHBoxLayout()
top_bar.addWidget(self.btn_open)
top_bar.addWidget(self.btn_open1)
top_bar.addWidget(self.btn_)
top_bar.addWidget(self.btn1)
top_bar.addWidget(self.btn2)
root = QVBoxLayout(self)
root.addLayout(top_bar)
root.addWidget(self.textbrowser)
self.spisok=list()
self.spisok2=list()
self.spisok3=list()
self.train=list()
self.matrix=list()
self.resize(540, 574)
self.setWindowTitle('ST_4')
self.show()
def openImages1(self):
filenames1 = QFileDialog.getOpenFileNames(None, 'Открыть изображения', '.', 'Image Files (*.png *.jpg *.jpeg *.bmp)')
lk=filenames1[0]
self.erroropened(lk,"1")
self.mass(lk,1)
lk.clear()
def openImages2(self):
filenames2 = QFileDialog.getOpenFileNames(None, 'Открыть изображения', '.', 'Image Files (*.png *.jpg *.jpeg *.bmp)')
lk=filenames2[0]
self.erroropened(lk,"2")
self.mass(lk,2)
lk.clear()
def erroropened(self,s,s1):
if len(s)!=0:
q=QMessageBox.information(self,"Информация","Изображения из "+s1+" папки получены!")
else:
q=QMessageBox.information(self,"Информация","Вы не выбрали изображения!")
def mass(self,p,s1):
if s1==1:
self.spisok3.clear()
for v in range(len(p)):
self.spisok.append(str(p[v]))
self.spisok3.append(str(p[v])+"SKT")
self.appendos("Тестовый набор картинок",self.spisok)
if s1==2:
for v in range(len(p)):
self.spisok2.append(str(p[v]))
self.spisok3.append(str(p[v])+"NO")
self.spisok3=list(set(self.spisok3))
self.appendos("Набор картинок для тренировки",self.spisok2)
self.btn_open.setVisible(False)
self.btn_open1.setVisible(False)
self.btn_.setVisible(True)
q=QMessageBox.information(self,"Информация","Количество изображений тестовой категории: "+str(len(self.spisok))+"\nКоличество изображений основной категории: "+str(len(self.spisok2))+"\nОбщее количество изображений: "+str(int(len(self.spisok)+int(len(self.spisok2)))))
def matrix_and_train(self):
for v in range(len(self.spisok3)):
s=str(self.spisok3[v])
if s.endswith("SKT"):
self.train.append(round(float(0.5),1))
self.matrix.append(round(float(1.0),1))
if s.endswith("NO"):
q=round(float(random.uniform(1.0,3.0)),1)
self.train.append(q)
self.matrix.append(round(float(-1.0),1))
self.appendos("Ваши тренировочные данные",self.train)
self.appendos("Ваша матрица",self.matrix)
train=np.array([self.train],dtype=int)
labels = np.array(self.matrix,dtype=int)
self.svm = cv2.ml.SVM_create()
self.svm.train(train, cv2.ml.COL_SAMPLE, labels)
self.svm.save("1.yml")
self.textbrowser.append("Модель сохранена!")
close = QMessageBox.question(self,"Поздравляем!","Ваша модель натренирована!",QMessageBox.Yes | QMessageBox.No)
if close == QMessageBox.Yes:
pass
self.btn_.setVisible(False)
self.btn1.setVisible(True)
def appendos(self,s1,s2):
self.textbrowser.append(s1)
for v in range(len(s2)):
self.textbrowser.append(str(s2[v]))
def detect_image(self):
self.model = RandomForestClassifier(n_estimators=100,bootstrap = True,max_features = 'sqrt')
self.spisok3.clear()
for v in range(len(self.spisok)):
lkst=list()
img = cv2.imread(str(self.spisok[v]))
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT_create()
kp = sift.detect(gray,None)
for keyPoint in kp:
#self.spisok3.append(keyPoint.pt[0])
#self.spisok3.append(keyPoint.pt[1])
#print(keyPoint.pt[0])
#print(keyPoint.pt[1])
lkst.append(keyPoint.pt[0])
lkst.append(keyPoint.pt[1])
#self.spisok3.append(lkst)
train=np.array([lkst],dtype=int)
labels = np.array([lkst],dtype=int)
self.model.fit(train, labels)
self.textbrowser.append("Модель натренирована на рисунке "+str(v))
#print(len(self.spisok3))
self.textbrowser.append("Выявлены контурные точки на тестовых изображениях!")
#s = keyPoint.size
#print(x,y,s)
self.btn1.setVisible(False)
self.btn2.setVisible(True)
def form_les_and_train(self):
#print(self.spisok3)
for v in range(len(self.spisok2)):
lk=list()
img = cv2.imread(str(self.spisok2[v]))
gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
sift = cv2.SIFT_create()
kp = sift.detect(gray,None)
for keyPoint in kp:
#self.spisok3.append(keyPoint.pt[0])
#self.spisok3.append(keyPoint.pt[1])
#print(keyPoint.pt[0])
#print(keyPoint.pt[1])
lkst.append(keyPoint.pt[0])
lkst.append(keyPoint.pt[1])
train =np.array([lkst],dtype=int)
self.model.predict(train)
#self.model.
print("RED")
#train = np.array([self.spisok3],dtype=int)
#labels = np.array([self.spisok3],dtype=int)
#model = RandomForestClassifier(n_estimators=100,bootstrap = True,max_features = 'sqrt')
#model.fit(train, labels)
#tree = DecisionTreeClassifier()
#tree.fit(self.spisok3, self.spisok3)
#accuracy = accuracy_score(len(self.spisok3), len(self.spisok3))
#print('Model Accuracy:',accuracy)
def closeEvent(self, event):
close = QMessageBox.question(self,"Выход","Вы хотите завершить работу?",QMessageBox.Yes | QMessageBox.No)
if close == QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Example()
sys.exit(app.exec_())

BIN
lab4/sift_keypoints.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

87
lab6_1/lab6_1.py Normal file
View File

@ -0,0 +1,87 @@
import os
import sys
import cv2
import numpy as np
from matplotlib import pyplot as plt
def main():
lstone=list()
lsttwo=list()
image1 = cv2.imread("D:\\MACH\\MACH\\LAB_2\\image0.jpg")
image2=image1
image3=image1
image4=image1
image5=image1
image6=image1
image7=image1
image2=erode_cv(image2,11)
image3=dilate_cv(image3,11)
image4=median_cv(image4,5)
image5=erode_ipp(image5,14)
image6=dilate_ipp(image6,14)
image7=median_ipp(image7,7)
cv2.imshow("Image_load",image1)
cv2.imshow("erode_cv",image2)
cv2.imshow("dilate_cv",image3)
cv2.imshow("median_cv",image4)
cv2.imshow("erode_ipp",image5)
cv2.imshow("dilate_ipp",image6)
cv2.imshow("median_ipp",image7)
cv2.waitKey(0)
lstone=sravit_metod(image2)
lsttwo=sravit_metod(image5)
lsttree=lsttwo[len(lstone):]
print("Erode")
print("Количество отличий : "+str(len(lsttwo)-len(lstone))+" \nРазница")
print(lsttree)
lstone=sravit_metod(image3)
lsttwo=sravit_metod(image5)
lsttree=lstone[len(lsttwo):]
print("Dilate")
print("Количество отличий : "+str(len(lstone)-len(lsttwo))+" \nРазница")
print(lsttree)
lstone=sravit_metod(image4)
lsttwo=sravit_metod(image7)
lsttree=lstone[len(lsttwo):]
print("Median")
print("Количество отличий : "+str(len(lstone)-len(lsttwo))+" \nРазница")
print(lsttree)
def erode_cv(s1,s2):
s1 = cv2.erode(s1, np.ones((s2, s2)))
return s1
def dilate_cv(s1,s2):
s1 = cv2.dilate(s1, np.ones((s2, s2)))
return s1
def median_cv(s1,s2):
s1 = cv2.medianBlur(s1,s2)
return s1
def erode_ipp(s1,s2):
s1 = cv2.erode(s1, np.ones((s2, s2)))
return s1
def dilate_ipp(s1,s2):
s1 = cv2.dilate(s1, np.ones((s2, s2)))
return s1
def median_ipp(s1,s2):
s1 = cv2.medianBlur(s1,s2)
return s1
def sravit_metod(s1):
cv2.imwrite("im1.jpg",s1)
s1 = cv2.imread("im1.jpg", 0)
th, threshed = cv2.threshold(s1, 100, 255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
t1= 3
t2 = 20
xcnts = []
for cnt in cnts:
if t1<cv2.contourArea(cnt) <t2:
xcnts.append(cnt)
os.remove("im1.jpg")
return xcnts
if __name__=="__main__":
main()

96
lab6_2/lab6_2.py Normal file
View File

@ -0,0 +1,96 @@
import os
import sys
import cv2
import numpy as np
from matplotlib import pyplot as plt
def main():
lstone=list()
lsttwo=list()
image1 = cv2.imread("D:\\MACH\\MACH\\LAB_2\\image0.jpg")
image2=image1
image3=image1
image4=image1
image5=image1
image6=image1
image7=image1
image2=erode_cv(image2,11)
image3=dilate_cv(image3,11)
image4=median_cv(image4,5)
image5=erode_ipp(image5,14)
image6=dilate_ipp(image6,14)
image7=median_ipp(image7,7)
x = np.linspace(-5, 2, 100) # от -5 до 2 сделать 100 точек
# показать рисунок
lstone=sravit_metod(image2)
lsttwo=sravit_metod(image5)
lsttree=lsttwo[len(lstone):]
y1 =len(lstone)*x
y2 =len(lsttree)*x
lstone=sravit_metod(image3)
lsttwo=sravit_metod(image5)
y3 =len(lstone)*x
y4 =len(lsttwo)*x
lstone=sravit_metod(image4)
lsttwo=sravit_metod(image7)
lsttree=lstone[len(lsttwo):]
y5 =len(lstone)*x
y6 =len(lsttwo)*x
fig, ax = plt.subplots()
ax.plot(x, y1, color="blue", label="erode_cv")
ax.plot(x, y2, color="red", label="erode_ipp")
ax.plot(x, y3, color="green", label="dilate_cv")
ax.plot(x, y4, color="yellow", label="dilate_ipp")
ax.plot(x, y5, color="orange", label="median_cv")
ax.plot(x, y6, color="grey", label="median_ipp")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()
def erode_cv(s1,s2):
s1 = cv2.erode(s1, np.ones((s2, s2)))
return s1
def dilate_cv(s1,s2):
s1 = cv2.dilate(s1, np.ones((s2, s2)))
return s1
def median_cv(s1,s2):
s1 = cv2.medianBlur(s1,s2)
return s1
def erode_ipp(s1,s2):
s1 = cv2.erode(s1, np.ones((s2, s2)))
return s1
def dilate_ipp(s1,s2):
s1 = cv2.dilate(s1, np.ones((s2, s2)))
return s1
def median_ipp(s1,s2):
s1 = cv2.medianBlur(s1,s2)
return s1
def sravit_metod(s1):
cv2.imwrite("im1.jpg",s1)
s1 = cv2.imread("im1.jpg", 0)
th, threshed = cv2.threshold(s1, 100, 255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
t1= 3
t2 = 20
xcnts = []
for cnt in cnts:
if t1<cv2.contourArea(cnt) <t2:
xcnts.append(cnt)
os.remove("im1.jpg")
return xcnts
if __name__=="__main__":
main()

3654
lab8/1.xml Normal file

File diff suppressed because it is too large Load Diff

18
lab8/lab8.py Normal file
View File

@ -0,0 +1,18 @@
import cv2
import numpy as np
from PIL import Image, ImageDraw
def main():
image = Image.open('D:\\MACH\\MACH\\LAB_2\\img1.jpg')
image_arr = np.asarray(image)
hog = cv2.HOGDescriptor()
hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
detections, weights = hog.detectMultiScale(image_arr)
detections_rectangles = detections.tolist()
draw = ImageDraw.Draw(image)
for x, y, w, h in detections_rectangles:
draw.rectangle(
[x, y, x + w, y + h], outline=(255, 0, 0))
image.show()
if __name__ == '__main__':
main()