-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathimage_pdi.py
200 lines (173 loc) · 7.54 KB
/
image_pdi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import os
import cv2
import numpy as np
from PIL import ImageFilter, Image as img
from matplotlib import pyplot as plt
class ImagePDI:
def __init__(self, filename):
self.image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
self.filename = filename
# definição do KERNEL/MÁSCARA
self.kernel = np.ones((6, 6), np.float32) / 25
def print_pixels(self):
# shape é um vetor --> índice p extrair o necessario
print("Altura: %d pixels" % (self.image.shape[0]))
print("Largura: %d pixels" % (self.image.shape[1]))
def set_kernel(self, altura, largura):
self.kernel = np.ones((altura, largura), np.float32) / 25
def power(self, const, gama, offset=None):
a = cv2.imread(self.filename, cv2.IMREAD_GRAYSCALE)
if offset is None:
x = const * (((a - a.min()) / (a.max() - a.min())) ** gama)
else:
x = const *\
((((a + offset) - a.min()) / (a.max() - a.min())) ** gama)
x = np.array(((a.max() - a.min()) * x) + a.min(), dtype=np.uint8)
newfilename = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(newfilename, x)
return newfilename
def min_filter(self, kernel): # aplicar o filtro MINIMO
im = img.open(self.filename)
image = im.filter(ImageFilter.MinFilter(kernel))
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
image.save(new_file_name)
return new_file_name
def max_filter(self, kernel): # aplicar o filtro MAXIMO
im = img.open(self.filename)
image = im.filter(ImageFilter.MaxFilter(kernel))
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
image.save(new_file_name)
return new_file_name
def media_filter(self, size): # aplicar o filtro da MÉDIA
blur = cv2.blur(self.image, (size, size))
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(new_file_name, blur)
return new_file_name
def median_filter(self, size): # aplicar o filtro da MEDIANA
# elimina eficientemento o ruído (sal e pimenta)
if(size % 2 == 0):
size += 1
median_blur = cv2.medianBlur(self.image, size)
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(new_file_name, median_blur)
return new_file_name
def filter2d(self, ddepth=-1): # CONVOLUÇÃO DISCRETA 2D
# toma como base a imagem e o valor definido no KERNEL
image = cv2.imread(self.filename)
cv2.filter2D(image, ddepth, self.kernel)
new_file_name = "./images/temporarias/"+os.path.basename(self.filename)
cv2.imwrite(new_file_name, image)
return new_file_name
def histogram(self):
plt.gcf().clear()
cv2.calcHist(self.image, [0], None, [256], [0, 256])
plt.hist(self.image.ravel(), 256, [0, 256])
plt.title('Histograma')
plt.xlabel('Valores dos pixels')
plt.ylabel('Qntd. de pixels')
plt.grid(True)
new_file_name = "./images/temporarias/histogram.jpg"
try:
os.remove(new_file_name)
except FileNotFoundError:
pass
plt.savefig(new_file_name)
return new_file_name
def histogram_bgr(self):
color = ('b', 'g', 'r')
for i, col in enumerate(color):
histogram = cv2.calcHist([self.image], [i], None, [256], [0, 256])
plt.plot(histogram, color=col)
plt.xlim([0, 256])
plt.title('Histograma: escala BGR')
plt.xlabel('Valores dos pixels')
plt.ylabel('Qntd. de pixels')
plt.grid(True)
plt.show()
def contours(self):
# CONTORNOS - Detector de Bordas
im = cv2.imread(self.filename)
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im_o, contours, hierarchy = cv2.findContours(
thresh,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
# contours --> é uma lista em Python de
# todos os contornos da imagem (contorno = matriz)
# Desenhando os CONTORNOS na Imagem:
img_cont = cv2.drawContours(im, contours, -1, (0, 255, 0), 3)
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(new_file_name, img_cont)
return new_file_name
# parametros: (imagem_origem, lista_contornos,
# índice (-1), cor, espessura...)
# cv2.imwrite("D:\imagem_cont.jpg", img_cont) SALVAR A IMAGEM
def contours_canny(self):
# Detecção de contornos pelo MÉTODO CANNY
image = cv2.imread(self.filename)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
suave = cv2.GaussianBlur(gray, (7, 7), 0)
canny = cv2.Canny(suave, 10, 30) # 20, 120 - menos mais bordas
result = np.vstack(canny)
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(new_file_name, result)
return new_file_name
# cv2.imwrite("D:\imagem_bordasCanny.jpg", result) SALVAR A IMAGEM
def equalize(self):
# EQUALIZAÇÃO DO HISTOGRAMA --> "esticar" o hist,
# evitar que fique concentrado apenas em um ponto alto
# Melhorar o contraste da imagem --> aumentar detalhes
plt.gcf().clear()
equa = cv2.equalizeHist(src=self.image)
cv2.calcHist(equa, [0], None, [256], [0, 256])
plt.hist(equa.ravel(), 256, [0, 256])
plt.title('Histograma Equalizado')
plt.xlabel('Valores dos pixels')
plt.ylabel('Qntd. de pixels')
plt.grid(True)
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(new_file_name, equa)
plt.savefig("./images/temporarias/histogram.jpg")
return new_file_name
# res = np.hstack((img, equa))
#colocar imagem original e equa lado a lado
# cv2.imwrite("D:\imagem_equalizada.jpg", res)
def fatiamento(self, plane):
a = self.image
# = np.array([[1, 2,3,4],[5,6,7,8]], dtype=np.uint8)
p = np.array(
[[int(np.binary_repr(a[i][j], 8)[8 - plane]) * 255
for j in range(0, a.shape[1])]
for i in range(0, a.shape[0])])
cv2.imwrite("./images/temporarias/"+str(plane)+".jpg", p)
return "./images/temporarias/"+str(plane)+".jpg"
def colorful(self, st):
st = st.replace(" ", "")
st = st.replace("(", "")
st = st.replace(")", "")
list_of_strings = st.split(";")
a = cv2.imread(self.filename)
rows, cols, c = a.shape
for i in range(0, rows):
for j in range(0, cols):
for k in list_of_strings:
e = k.split(",")
max_value = int(e[1])
min_value = int(e[0])
if (a[i][j][0] >= min_value) and (a[i][j][0] <= max_value):
a[i][j] = [int(e[2]), int(e[3]), int(e[4])]
new_file_name = "./images/temporarias/" + os.path.basename(self.filename)
cv2.imwrite(new_file_name, a)
return new_file_name
def gaussian_noise(self):
pass
def impulsive_noise(self):
pass
def geometric_filter(self):
pass
def trimmed_filter(self):
pass
if __name__=="__main__":
y = ImagePDI("./images/images_chapter_03/Fig3.35(a).jpg")
y.media_filter(35)