Monday, December 14, 2020

Edge Detection, Segmentation, and Denoising on Images with Python GUI (PyQt): Part 4

This content is powered by Balige PublishingVisit this link

Part 1 Part 2 Part 3


Tutorial Steps To Implement Image Denoising Using Non-local Means Denoising, Total Variation Filter, Bilateral Filter, and Wavelet Denoising Filter.

First, use cv2.fastNlMeansDenoisingColored() function which is the implementation of Non-local Means Denoising algorithm as defined below:

cv2.fastNlMeansDenoisingColored(src[, dst[, \
   h[, hColor[, templateWindowSize[, searchWindowSize]]]]])

The parameters are:


The three other algorithms you will use in this project are total variation filter, bilateral filter, and wavelet denoising filter. You need to import the three algorithms using this import statement as follows:

from skimage.restoration import (denoise_tv_chambolle,\
denoise_bilateral, denoise_wavelet, estimate_sigma)

Add a Combo Box widget onto form in Qt Designer. Set its objectName property as cboDenoising. Double click on that widget and add four items as shown in Figure below.


Add five new Label widgets and set their text properties as h, patch, search, weight, and sigma.

Add a new Spin Box widget and set its objectName property as sbH. Set its value property to 15, its minimum property to 3, its maximum property to 99, and its singleStep to 1.

Add another Spin Box widget and set its objectName property as sbPatch. Set its value property to 13, its minimum property to 3, its maximum property to 99, and its singleStep to 2.

Add another Spin Box widget and set its objectName property as sbSearch. Set its value property to 29, its minimum property to 3, its maximum property to 99, and its singleStep to 2.

Add a new Horizonal Slider widget and set its objectName property as hsWeight. Set its value property to 0, its minimum property to 0, its maximum property to 10, and its singleStep to 1.

Add a new Horizonal Slider widget and set its objectName property as hsSigma. Set its value property to 0, its minimum property to 0, its maximum property to 100, and its singleStep to 1.

Add two new Line Edit widgets and set their objectName properties to leWeight and leSigma. Set their text properties to 0.1 and 0.25. The newly modified form is shown in Figure below


Define a new method, choose_denoising(), to read currentText property of cboDenoising and implement image denoising accordingly:

def choose_denoising(self,img):
strCB = self.cboDenoising.currentText()
h = self.sbH.value()
patch = self.sbPatch.value()
size = self.sbSearch.value()
weightVal = float(self.leWeight.text())
sigmaVal = float(self.leSigma.text())
noisy = self.choose_noise(img)
if strCB == 'Non-Local Means Denoising':
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
self.sbH.setEnabled(True)
self.sbPatch.setEnabled(True)
self.sbSearch.setEnabled(True)
denoised_img = cv2.fastNlMeansDenoisingColored(\
noisy,None,h,h,patch,size)
return denoised_img
if strCB == 'Total Variation Filter':
self.hsWeight.setEnabled(True)
self.leWeight.setEnabled(True)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
denoised_img = denoise_tv_chambolle(noisy, \
weight=weightVal, multichannel=True)
cv2.normalize(denoised_img, \
denoised_img, 0, 255, cv2.NORM_MINMAX, dtype=-1)
denoised_img = denoised_img.astype(np.uint8)
return denoised_img
if strCB == 'Bilateral Filter':
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsSigma.setEnabled(True)
self.leSigma.setEnabled(True)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
denoised_img = denoise_bilateral(noisy, \
sigma_color=sigmaVal, sigma_spatial=15, \
multichannel=True)
cv2.normalize(denoised_img, \
denoised_img, 0, 255, cv2.NORM_MINMAX, dtype=-1)
denoised_img = denoised_img.astype(np.uint8)
return denoised_img
if strCB == 'Wavelet Denoising Filter':
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
denoised_img = denoise_wavelet(noisy, \
multichannel=True, convert2ycbcr=True, \
rescale_sigma=True)
cv2.normalize(denoised_img, denoised_img, 0, 255, \
cv2.NORM_MINMAX, dtype=-1)
denoised_img = denoised_img.astype(np.uint8)
return denoised_img

Define a new method, do_denoising(), to call choose_denoising() and convert the result from BGR into RGB color space:

def do_denoising(self):
denoised = self.choose_denoising(img)
height, width, channel = denoised.shape
bytesPerLine = 3 * width
cv2.cvtColor(denoised, cv2.COLOR_BGR2RGB, denoised)
qImg = QImage(denoised, width, height, \
bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qImg)
self.display_image(pixmap, denoised, self.labelImage, \
self.widgetHistFilter, 'Histogram of Denoised Image')

Define two new methods, set_hsWeight() and set_hsSigma(), to set text properties of leWeight and leSigma and to invoke do_denoising() method.

def set_hsWeight(self, value):
self.leWeight.setText(str(round((value/10),2)))
self.do_denoising()
def set_hsSigma(self, value):
self.leSigma.setText(str(round((value/100),2)))
self.do_denoising()

Connect currentIndexChanged() event of cboDenoising to do_denoising(). Connect valueChanged() event of sbH, sbPatch, and sbSearch to do_denoising(). Put them inside __init__() method as follows:

self.cboDenoising.currentIndexChanged.connect(self.do_denoising)
self.sbH.valueChanged.connect(self.do_denoising)
self.sbPatch.valueChanged.connect(self.do_denoising)
self.sbSearch.valueChanged.connect(self.do_denoising)

Connect valueChanged() event of hsWeight to set_hsWeight() and valueChanged() event of hsSigma to set_hsSigma(). Put them inside __init__() method as follows:

self.hsWeight.valueChanged.connect(self.set_hsWeight)
self.hsSigma.valueChanged.connect(self.set_hsSigma)

Run image_processing.py. Choose test image and select Gaussian noise type to generate noisy image. Then select Non-Local Means Denoising and you can select h, patch, and search values that suit you better. The result is shown in Figure below.


Then select Total Variation Filter and you can select weight value that suits you better. The result is shown in Figure below.


Choose another test image and select Salt & Pepper noise type to generate noisy image. Then select Bilateral Filter and you can select sigma value that suits you better. The result is shown in Figure below.


Then select Wavelet Denoising Filter. The result is shown in Figure below.


The following is the last version of image_processing.py script:

1
2
4
3 5
8
6 7 9
13
10 11 12 14
19
15 16 17 18 20
26
21 22 23 24 25 27
34
28 29 30 31 32 33 35
43
36 37 38 39 40 41 42 44
53
45 46 47 48 49 50 51 52 54
64
55 56 57 58 59 60 61 62 63 65
76
66 67 68 69 70 71 72 73 74 75 77
89
78 79 80 81 82 83 84 85 86 87 88 90
103
91 92 93 94 95 96 97 98 99 100 101 102 104
118
105 106 107 108 109 110 111 112 113 114 115 116 117 119
134
120 121 122 123 124 125 126 127 128 129 130 131 132 133 135
151
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 152
169
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 170
188
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 189
208
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 209
229
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 230
251
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 252
274
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 275
298
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 299
323
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 324
349
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 350
376
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 377
404
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 405
433
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 434
463
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 464
494
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 495
526
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 527
555
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
554
#image_processing.py
import cv2
import numpy as np
from PyQt5.QtWidgets import*
from PyQt5 import QtGui, QtCore
from PyQt5.uic import loadUi
from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar)
from PyQt5.QtWidgets import QDialog, QFileDialog
from PyQt5.QtGui import QIcon, QPixmap, QImage
from PIL import Image
from skimage.util import random_noise
from sklearn.cluster import KMeans
from skimage.filters import gaussian
import skimage.color as color
import numpy as np
from skimage.restoration import (denoise_tv_chambolle, denoise_bilateral, denoise_wavelet, estimate_sigma)
fname = ""
class FormImageProcessing(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("image_proc.ui",self)
self.setWindowTitle("Image Processing")
self.pbImage.clicked.connect(self.open_file)
self.setState('START')
self.hsMean.valueChanged.connect(self.set_hsMean)
self.hsVar.valueChanged.connect(self.set_hsVar)
self.hsAmount.valueChanged.connect(self.set_hsAmount)
self.leMean.textEdited.connect(self.do_noise)
self.leVar.textEdited.connect(self.do_noise)
self.leAmount.textEdited.connect(self.do_noise)
self.cboNoise.currentIndexChanged.connect(self.do_noise)
self.sbMinVal.valueChanged.connect(self.set_minval)
self.sbMaxVal.valueChanged.connect(self.set_maxval)
self.sbKernel.valueChanged.connect(self.set_kernel)
self.leMinVal.textEdited.connect(self.do_edge)
self.leMaxVal.textEdited.connect(self.do_edge)
self.leKernel.textEdited.connect(self.do_edge)
self.cboEdge.currentIndexChanged.connect(self.do_edge)
self.rbMultiple.toggled.connect(self.rbstate)
self.rbKMeans.toggled.connect(self.rbstate)
self.cboDenoising.currentIndexChanged.connect(self.do_denoising)
self.sbH.valueChanged.connect(self.do_denoising)
self.sbPatch.valueChanged.connect(self.do_denoising)
self.sbSearch.valueChanged.connect(self.do_denoising)
self.hsWeight.valueChanged.connect(self.set_hsWeight)
self.hsSigma.valueChanged.connect(self.set_hsSigma)
def set_hsWeight(self, value):
self.leWeight.setText(str(round((value/10),2)))
self.do_denoising()
def set_hsSigma(self, value):
self.leSigma.setText(str(round((value/100),2)))
self.do_denoising()
def choose_denoising(self,img):
strCB = self.cboDenoising.currentText()
h = self.sbH.value()
patch = self.sbPatch.value()
size = self.sbSearch.value()
weightVal = float(self.leWeight.text())
sigmaVal = float(self.leSigma.text())
noisy = self.choose_noise(img)
if strCB == 'Non-Local Means Denoising':
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
self.sbH.setEnabled(True)
self.sbPatch.setEnabled(True)
self.sbSearch.setEnabled(True)
denoised_img = cv2.fastNlMeansDenoisingColored(noisy,None,\
h,h,patch,size)
return denoised_img
if strCB == 'Total Variation Filter':
self.hsWeight.setEnabled(True)
self.leWeight.setEnabled(True)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
denoised_img = denoise_tv_chambolle(noisy, \
weight=weightVal, multichannel=True)
cv2.normalize(denoised_img, denoised_img, 0, 255, \
cv2.NORM_MINMAX, dtype=-1)
denoised_img = denoised_img.astype(np.uint8)
return denoised_img
if strCB == 'Bilateral Filter':
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsSigma.setEnabled(True)
self.leSigma.setEnabled(True)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
denoised_img = denoise_bilateral(noisy, sigma_color=sigmaVal, \
sigma_spatial=25, multichannel=True)
cv2.normalize(denoised_img, denoised_img, 0, 255, \
cv2.NORM_MINMAX, dtype=-1)
denoised_img = denoised_img.astype(np.uint8)
return denoised_img
if strCB == 'Wavelet Denoising Filter':
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
denoised_img = denoise_wavelet(noisy, multichannel=True, \
convert2ycbcr=True, rescale_sigma=True)
cv2.normalize(denoised_img, denoised_img, 0, 255, \
cv2.NORM_MINMAX, dtype=-1)
denoised_img = denoised_img.astype(np.uint8)
return denoised_img
def do_denoising(self):
denoised = self.choose_denoising(img)
height, width, channel = denoised.shape
bytesPerLine = 3 * width
cv2.cvtColor(denoised, cv2.COLOR_BGR2RGB, denoised)
qImg = QImage(denoised, width, height, \
bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qImg)
self.display_image(pixmap, denoised, self.labelImage, \
self.widgetHistFilter, 'Histogram of Denoised Image')
def thresh_seg(self,img):
img_seg = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
img_seg = self.multiple_thresh(img)
else:
img_seg[:, :, 0] = self.multiple_thresh(img[:, :, 0])
img_seg[:, :, 1] = self.multiple_thresh(img[:, :, 1])
img_seg[:, :, 2] = self.multiple_thresh(img[:, :, 2])
cv2.normalize(img_seg, img_seg, 0, 255, cv2.NORM_MINMAX, dtype=-1)
img_seg = img_seg.astype(np.uint8)
return img_seg
def multiple_thresh(self, img):
img_thresh= 255*img.reshape(img.shape[0]*img.shape[1])
thresh_mean = img_thresh.mean()
for i in range(img_thresh.shape[0]):
if img_thresh[i] > thresh_mean:
img_thresh[i] = 3
elif img_thresh[i] > 0.5:
img_thresh[i] = 2
elif img_thresh[i] > 0.25:
img_thresh[i] = 1
else:
img_thresh[i] = 0
img_mul = img_thresh.reshape(img.shape[0],img.shape[1])
return img_mul
def kmeans_seg(self,img):
img_seg = np.zeros(img.shape, np.float32)
img_n = img.reshape(img.shape[0]*img.shape[1], img.shape[2])
kmeans = KMeans(n_clusters=5, random_state=0).fit(img_n)
pic2show = kmeans.cluster_centers_[kmeans.labels_]
img_seg = pic2show.reshape(img.shape[0], img.shape[1], img.shape[2])
cv2.normalize(img_seg, img_seg, 0, 255, cv2.NORM_MINMAX, dtype=-1)
img_seg = img_seg.astype(np.uint8)
return img_seg
def rbstate(self):
noisy = self.choose_noise(img)
if self.rbMultiple.isChecked() == True:
output = self.thresh_seg(noisy)
self.seg_output(output)
if self.rbKMeans.isChecked() == True:
output = self.kmeans_seg(noisy)
self.seg_output(output)
def seg_output(self,output):
height, width, channel = output.shape
bytesPerLine = 3 * width
cv2.cvtColor(output, cv2.COLOR_BGR2RGB, output)
qImg = QImage(output, width, height, \
bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qImg)
self.display_image(pixmap, output, self.labelFilter, \
self.widgetHistFilter, 'Histogram of Segmented Image')
def open_file(self):
global img
self.fname = QFileDialog.getOpenFileName(self, 'Open file',
'd:\\',"Image Files (*.jpg *.gif *.bmp *.png)")
pixmap = QPixmap(self.fname[0])
img = cv2.imread(self.fname[0], cv2.IMREAD_COLOR)
self.display_image(pixmap, img, self.labelImage, \
self.widgetHistIm, 'Histogram of Original Image')
self.setState('RUN')
self.hsAmount.setEnabled(False)
self.leAmount.setEnabled(False)
def display_image(self, pixmap, img, label, qwidget1, title):
label.setPixmap(pixmap)
label.setScaledContents(True);
self.display_histogram(img, qwidget1, title)
def display_histogram(self, img, qwidget1, title):
qwidget1.canvas.axes1.clear()
channel = len(img.shape)
if channel == 2: #grayscale image
histr = cv2.calcHist([img],[0],None,[256],[0,256])
qwidget1.canvas.axes1.plot(histr,\
color = 'yellow',linewidth=3.0)
qwidget1.canvas.axes1.set_ylabel('Frequency',\
color='white')
qwidget1.canvas.axes1.set_xlabel('Intensity', \
color='white')
qwidget1.canvas.axes1.tick_params(axis='x', colors='white')
qwidget1.canvas.axes1.tick_params(axis='y', colors='white')
qwidget1.canvas.axes1.set_title(title,color='white')
qwidget1.canvas.axes1.set_facecolor('xkcd:black')
qwidget1.canvas.axes1.grid()
qwidget1.canvas.draw()
else : #color image
color = ('b','g','r')
for i,col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,256])
qwidget1.canvas.axes1.plot(histr,\
color = col,linewidth=3.0)
qwidget1.canvas.axes1.set_ylabel('Frequency',\
color='white')
qwidget1.canvas.axes1.set_xlabel('Intensity', \
color='white')
qwidget1.canvas.axes1.tick_params(axis='x', colors='white')
qwidget1.canvas.axes1.tick_params(axis='y', colors='white')
qwidget1.canvas.axes1.set_title(title,color='white')
qwidget1.canvas.axes1.set_facecolor('xkcd:black')
qwidget1.canvas.axes1.grid()
qwidget1.canvas.draw()
def setState(self, state):
if state == 'START':
self.cboNoise.setEnabled(False)
self.hsMean.setEnabled(False)
self.hsVar.setEnabled(False)
self.hsAmount.setEnabled(False)
self.leMean.setEnabled(False)
self.leVar.setEnabled(False)
self.leAmount.setEnabled(False)
self.leMinVal.setEnabled(False)
self.leMaxVal.setEnabled(False)
self.leKernel.setEnabled(False)
self.sbMinVal.setEnabled(False)
self.sbMaxVal.setEnabled(False)
self.sbKernel.setEnabled(False)
self.cboEdge.setEnabled(False)
self.rbMultiple.setEnabled(False)
self.rbKMeans.setEnabled(False)
self.cboDenoising.setEnabled(False)
self.sbH.setEnabled(False)
self.sbPatch.setEnabled(False)
self.sbSearch.setEnabled(False)
self.hsWeight.setEnabled(False)
self.leWeight.setEnabled(False)
self.hsWeight.setEnabled(False)
self.hsSigma.setEnabled(False)
self.leSigma.setEnabled(False)
else:
self.cboNoise.setEnabled(True)
self.hsMean.setEnabled(True)
self.hsVar.setEnabled(True)
self.hsAmount.setEnabled(True)
self.leMean.setEnabled(True)
self.leVar.setEnabled(True)
self.leAmount.setEnabled(True)
self.leMinVal.setEnabled(True)
self.leMaxVal.setEnabled(True)
self.leKernel.setEnabled(True)
self.sbMinVal.setEnabled(True)
self.sbMaxVal.setEnabled(True)
self.sbKernel.setEnabled(True)
self.cboEdge.setEnabled(True)
self.rbMultiple.setEnabled(True)
self.rbKMeans.setEnabled(True)
self.cboDenoising.setEnabled(True)
self.sbH.setEnabled(True)
self.sbPatch.setEnabled(True)
self.sbSearch.setEnabled(True)
self.hsWeight.setEnabled(True)
self.leWeight.setEnabled(True)
self.hsWeight.setEnabled(True)
self.hsSigma.setEnabled(True)
self.leSigma.setEnabled(True)
def set_hsMean(self, value):
self.leMean.setText(str(round((value/64),2)))
self.do_noise()
def set_hsVar(self, value):
self.leVar.setText(str(round((value/64),2)))
self.do_noise()
def set_hsAmount(self, value):
self.leAmount.setText(str(round((value/10),2)))
self.do_noise()
def choose_noise(self,img):
strCB = self.cboNoise.currentText()
mean = float(self.leMean.text())
var = float(self.leVar.text())
amount = float(self.leAmount.text())
sigma = var**0.5
row,col,ch= img.shape
if strCB == 'Gaussian':
self.hsAmount.setEnabled(False)
self.leAmount.setEnabled(False)
self.hsMean.setEnabled(True)
self.leMean.setEnabled(True)
self.hsVar.setEnabled(True)
self.leVar.setEnabled(True)
noisy_image = self.gaussian_noise(img, mean, sigma, row, col)
return noisy_image
if strCB == 'Speckle':
self.hsAmount.setEnabled(False)
self.leAmount.setEnabled(False)
self.hsMean.setEnabled(True)
self.leMean.setEnabled(True)
self.hsVar.setEnabled(True)
self.leVar.setEnabled(True)
noisy_image = self.speckle_noise(img, mean, sigma, row, col)
return noisy_image
if strCB == 'Poisson':
self.hsMean.setEnabled(False)
self.leMean.setEnabled(False)
self.hsVar.setEnabled(False)
self.leVar.setEnabled(False)
self.hsAmount.setEnabled(True)
self.leAmount.setEnabled(True)
noisy_image = self.poisson_noise(img, amount)
return noisy_image
if strCB == 'Salt & Pepper':
self.hsMean.setEnabled(False)
self.leMean.setEnabled(False)
self.hsVar.setEnabled(False)
self.leVar.setEnabled(False)
self.hsAmount.setEnabled(True)
self.leAmount.setEnabled(True)
noisy_image = self.salt_pepper_noise(img, amount)
return noisy_image
def gaussian_noise2(self,img, mean, sigma, row, col):
gaussian = np.random.normal(mean, sigma, \
(row,col)) # np.zeros((224, 224), np.float32)
noisy_image = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
noisy_image = img + gaussian
else:
noisy_image[:, :, 0] = img[:, :, 0] + gaussian
noisy_image[:, :, 1] = img[:, :, 1] + gaussian
noisy_image[:, :, 2] = img[:, :, 2] + gaussian
cv2.normalize(noisy_image, noisy_image, 0, 255, \
cv2.NORM_MINMAX, dtype=-1)
noisy_image = noisy_image.astype(np.uint8)
return noisy_image
def speckle_noise2(self,img, mean, sigma, row, col):
gaussian = np.random.normal(mean, sigma, \
(row,col)) # np.zeros((224, 224), np.float32)
noisy_image = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
noisy_image = img + img*gaussian
else:
noisy_image[:, :, 0] = img[:, :, 0] + gaussian * img[:, :, 0]
noisy_image[:, :, 1] = img[:, :, 1] + gaussian * img[:, :, 1]
noisy_image[:, :, 2] = img[:, :, 2] + gaussian * img[:, :, 2]
cv2.normalize(noisy_image, noisy_image, 0, 255, \
cv2.NORM_MINMAX, dtype=-1)
noisy_image = noisy_image.astype(np.uint8)
return noisy_image
def gaussian_noise(self,img, mean, sigma, row, col):
# Generate Gaussian noise
gauss = np.random.normal(mean,sigma,img.size)
gauss = gauss.reshape(img.shape[0],img.shape[1],\
img.shape[2]).astype('uint8')
# Add the Gaussian noise to the image
img_gauss = cv2.add(img,gauss)
return img_gauss
def speckle_noise(self,img, mean, sigma, row, col):
# Generate Gaussian noise
gauss = np.random.normal(mean,sigma,img.size)
gauss = gauss.reshape(img.shape[0],img.shape[1],\
img.shape[2]).astype('uint8')
# Add the Gaussian noise to the image
img_sp = cv2.add(img,img*gauss)
return img_sp
def salt_pepper_noise(self, img, val):
# Add salt-and-pepper noise to the image.
noise_img = random_noise(img, mode='s&p',amount=val)
# The above function returns a floating-point image
# on the range [0, 1], thus we changed it to 'uint8'
# and from [0,255]
imgsnp = np.array(255*noise_img, dtype = 'uint8')
return imgsnp
def poisson_noise(self, img, peak):
pois = np.random.poisson(img / 255.0 * peak) / peak * 255
# The above function returns a floating-point image
# on the range [0, 1], thus we changed it to 'uint8'
# and from [0,255]
imgpois = np.array(255*pois, dtype = 'uint8')
return imgpois
def do_noise(self):
noisy = self.choose_noise(img)
height, width, channel = noisy.shape
bytesPerLine = 3 * width
cv2.cvtColor(noisy, cv2.COLOR_BGR2RGB, noisy)
qImg = QImage(noisy, width, height, \
bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qImg)
self.display_image(pixmap, noisy, self.labelFilter, \
self.widgetHistFilter, 'Histogram of Noisy Image')
def choose_edge(self,img):
strCB = self.cboEdge.currentText()
minVal = float(self.leMinVal.text())
maxVal = float(self.leMaxVal.text())
kernel = int(self.leKernel.text())
noisy = self.choose_noise(img)
if strCB == 'Canny':
self.leKernel.setEnabled(False)
self.sbKernel.setEnabled(False)
self.leMinVal.setEnabled(True)
self.sbMinVal.setEnabled(True)
self.leMaxVal.setEnabled(True)
self.sbMaxVal.setEnabled(True)
edge_im = self.canny_edge(noisy, minVal, maxVal)
return edge_im
if strCB == 'Sobel X':
self.leKernel.setEnabled(True)
self.sbKernel.setEnabled(True)
self.leMinVal.setEnabled(False)
self.sbMinVal.setEnabled(False)
self.leMaxVal.setEnabled(False)
self.sbMaxVal.setEnabled(False)
edge_im = self.sobelx_edge(noisy, 1, 0, kernel)
return edge_im
if strCB == 'Sobel Y':
self.leKernel.setEnabled(True)
self.sbKernel.setEnabled(True)
self.leMinVal.setEnabled(False)
self.sbMinVal.setEnabled(False)
self.leMaxVal.setEnabled(False)
self.sbMaxVal.setEnabled(False)
edge_im = self.sobelx_edge(noisy, 0, 1, kernel)
return edge_im
if strCB == 'Laplacian':
self.leKernel.setEnabled(True)
self.sbKernel.setEnabled(True)
self.leMinVal.setEnabled(False)
self.sbMinVal.setEnabled(False)
self.leMaxVal.setEnabled(False)
self.sbMaxVal.setEnabled(False)
edge_im = self.laplacian_edge(noisy, kernel)
return edge_im
def canny_edge(self, img, minVal, maxVal):
edge_im = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
edge_im = cv2.Canny(img,minVal, maxVal)
else:
edge_im[:, :, 0] = cv2.Canny(img[:, :, 0],minVal, maxVal)
edge_im[:, :, 1] = cv2.Canny(img[:, :, 1],minVal, maxVal)
edge_im[:, :, 2] = cv2.Canny(img[:, :, 2],minVal, maxVal)
cv2.normalize(edge_im, edge_im, 0, 255, cv2.NORM_MINMAX, dtype=-1)
edge_im = edge_im.astype(np.uint8)
return edge_im
def sobelx_edge(self, img, d1, d2, kernel):
edge_im = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
edge_im = cv2.Sobel(img,cv2.CV_64F, d1, d2, kernel)
else:
edge_im[:, :, 0] = cv2.Sobel(img[:, :, 0],cv2.CV_64F, d1, d2, kernel)
edge_im[:, :, 1] = cv2.Sobel(img[:, :, 1],cv2.CV_64F, d1, d2, kernel)
edge_im[:, :, 2] = cv2.Sobel(img[:, :, 2],cv2.CV_64F, d1, d2, kernel)
cv2.normalize(edge_im, edge_im, 0, 255, cv2.NORM_MINMAX, dtype=-1)
edge_im = edge_im.astype(np.uint8)
return edge_im
def laplacian_edge(self, img, kernel):
edge_im = np.zeros(img.shape, np.float32)
if len(img.shape) == 2:
edge_im = cv2.Laplacian(img, cv2.CV_64F, kernel)
else:
edge_im[:, :, 0] = cv2.Laplacian(img[:, :, 0], cv2.CV_64F, kernel)
edge_im[:, :, 1] = cv2.Laplacian(img[:, :, 1], cv2.CV_64F, kernel)
edge_im[:, :, 2] = cv2.Laplacian(img[:, :, 2], cv2.CV_64F, kernel)
cv2.normalize(edge_im, edge_im, 0, 255, cv2.NORM_MINMAX, dtype=-1)
edge_im = edge_im.astype(np.uint8)
return edge_im
def do_edge(self):
edges = self.choose_edge(img)
height, width, channel = edges.shape
bytesPerLine = 3 * width
cv2.cvtColor(edges, cv2.COLOR_BGR2RGB, edges)
qImg = QImage(edges, width, height, \
bytesPerLine, QImage.Format_RGB888)
pixmap = QPixmap.fromImage(qImg)
self.display_image(pixmap, edges, self.labelFilter, \
self.widgetHistFilter, 'Histogram of Edge Detection')
def set_minval(self):
self.leMinVal.setText(str(self.sbMinVal.value()))
self.do_edge()
def set_maxval(self):
self.leMaxVal.setText(str(self.sbMaxVal.value()))
self.do_edge()
def set_kernel(self):
self.leKernel.setText(str(self.sbKernel.value()))
self.do_edge()
if __name__=="__main__":
import sys
app = QApplication(sys.argv)
w = FormImageProcessing()
w.show()
sys.exit(app.exec_())





No comments:

Post a Comment