Advertisement
Aseron

DIGIKEP

Apr 10th, 2019
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.74 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3.  
  4. def addPointNoise(img, percentage, value):
  5.     noise = np.copy(img)
  6.     n = int(img.shape[0] * img.shape[1] * percentage)
  7.     print(n)
  8.  
  9.     for k in range(1, n):
  10.         i = np.random.randint(0, img.shape[1])
  11.         j = np.random.randint(0, img.shape[0])
  12.  
  13.         if img.ndim == 2:
  14.             noise[j, i] = value
  15.  
  16.         if img.ndim == 3:
  17.             noise[j, i] = [value, value, value]
  18.  
  19.     return noise
  20.  
  21.  
  22. def addSaltAndPepperNoise(img, percentage1, percentage2):
  23.     n = addPointNoise(img, percentage1, 255) # Só
  24.     n2 = addPointNoise(n, percentage2, 0) # Bors
  25.     return n2
  26.  
  27.  
  28. img = cv2.imread('Grape.jpg',cv2.IMREAD_GRAYSCALE);
  29.  
  30. imnoisegauss5x5 = cv2.GaussianBlur(img, (5, 5), sigmaX=2.0, sigmaY=2.0)
  31.  
  32. threshold, im_thresh = cv2.threshold(imnoisegauss5x5, 170, 255, cv2.THRESH_BINARY)
  33.  
  34. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
  35. dst = cv2.dilate(im_thresh,kernel,iterations=1)
  36. dst = cv2.erode(dst,kernel,iterations=2)
  37. dst = cv2.dilate(dst,kernel,iterations=1)
  38.  
  39. dstinv = 255-dst
  40.  
  41. blurred = cv2.GaussianBlur(dstinv, (5, 5), 2.0)
  42. edges = cv2.Canny(blurred, 100, 200, None, 5, True)
  43.  
  44. img_ocv_edge = cv2.cvtColor(img.copy(),cv2.COLOR_GRAY2BGR)
  45. b, g, r = cv2.split(img_ocv_edge)
  46. r = cv2.bitwise_and(r, ~edges)
  47. g = cv2.bitwise_or(g, edges)
  48. b = cv2.bitwise_and(b, ~edges)
  49. img_ocv_edge = cv2.merge((b, g, r))
  50.  
  51. cv2.imwrite('done.jpg',img_ocv_edge)
  52.  
  53. cv2.imshow('img', img)
  54. cv2.waitKey(0)
  55. cv2.imshow('img', imnoisegauss5x5)
  56. cv2.waitKey(0)
  57. cv2.imshow('img', im_thresh)
  58. cv2.waitKey(0)
  59. cv2.imshow('img', dst)
  60. cv2.waitKey(0)
  61. cv2.imshow('img', dstinv)
  62. cv2.waitKey(0)
  63. cv2.imshow('img', edges)
  64. cv2.waitKey(0)
  65. cv2.imshow('img', img_ocv_edge)
  66. cv2.waitKey(0)
  67.  
  68. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement