Guest User

Untitled

a guest
Jan 18th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. img = cv2.imread('lena.jpg')
  2. mask = cv2.imread('mask.png',0)
  3. res = cv2.bitwise_and(img,img,mask = mask)
  4.  
  5. # http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
  6. import cv2
  7. import numpy as np
  8.  
  9. # load the image
  10. img = cv2.imread('E:\FOTOS\opencv\opencv_logo.png')
  11. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  12.  
  13. # detect circles
  14. gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
  15. circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
  16. circles = np.uint16(np.around(circles))
  17.  
  18. # draw mask
  19. mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) # mask is only
  20. for i in circles[0, :]:
  21. cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
  22.  
  23. # get first masked value (foreground)
  24. fg = cv2.bitwise_or(img, img, mask=mask)
  25.  
  26. # get second masked value (background) mask must be inverted
  27. mask = cv2.bitwise_not(mask)
  28. background = np.full(img.shape, 255, dtype=np.uint8)
  29. bk = cv2.bitwise_or(background, background, mask=mask)
  30.  
  31. # combine foreground+background
  32. final = cv2.bitwise_or(fg, bk)
  33.  
  34. assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
  35. assert len(foreground_rgb.shape) == 3
  36. assert len(background_rgb.shape) == 3
  37.  
  38. alpha3 = np.stack([mask]*3, axis=2)
  39. blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb
  40.  
  41. alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))
  42.  
  43. x, y = np.where(mask!=0)
  44. pts = zip(x, y)
  45. # Assuming dst and src are of same sizes
  46. for pt in pts:
  47. dst[pt] = src[pt]
  48.  
  49. idx = (mask!=0)
  50. dst[idx] = src[idx]
  51.  
  52. import cv2 as cv
  53.  
  54. im_color = cv.imread("lena.png", cv.IMREAD_COLOR)
  55. im_gray = cv.cvtColor(im_color, cv.COLOR_BGR2GRAY)
  56.  
  57. _, mask = cv.threshold(im_gray, thresh=180, maxval=255, type=cv.THRESH_BINARY)
  58. im_thresh_gray = cv.bitwise_and(im_gray, mask)
  59.  
  60. mask3 = cv.cvtColor(mask, cv.COLOR_GRAY2BGR) # 3 channel mask
  61.  
  62. im_thresh_color = cv.bitwise_and(im_color, mask3)
  63.  
  64. cv.imshow("original image", im_color)
  65. cv.imshow("binary mask", mask)
  66. cv.imshow("3 channel mask", mask3)
  67. cv.imshow("im_thresh_gray", im_thresh_gray)
  68. cv.imshow("im_thresh_color", im_thresh_color)
  69. cv.waitKey(0)
Add Comment
Please, Sign In to add comment