Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3. from matplotlib import pyplot as plt
  4.  
  5. img = cv2.imread('der.jpg')
  6. plt.imshow(img)
  7. plt.show()
  8.  
  9. mask = np.zeros(img.shape[:2],np.uint8)
  10.  
  11. bgdModel = np.zeros((1,65),np.float64)
  12. fgdModel = np.zeros((1,65),np.float64)
  13.  
  14. rect = (500,400,1000,1250)
  15.  
  16. cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
  17.  
  18. mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
  19. img = img*mask2[:,:,np.newaxis]
  20. plt.imshow(img),plt.colorbar(),plt.show()
  21.  
  22. img2 = cv2.imread('der2.jpg',0)
  23. # whereever it is marked white (sure foreground), change mask=1
  24. # whereever it is marked black (sure background), change mask=0
  25. print(mask.shape)
  26. print(img2.shape)
  27. mask[img2 == 0] = 0
  28. mask, bgdModel, fgdModel = cv2.grabCut(img,mask,None,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_MASK)
  29. mask = np.where((mask==2)|(mask==0),0,1).astype('uint8')
  30. img = img*mask[:,:,np.newaxis]
  31. indices = np.column_stack(np.where(img != 0))
  32. print(indices)
  33. #top = max(indices[:,1])
  34. #bot = min(indices[:,1])
  35. #left = max(indices[:,0])
  36. #right = min(indices[:,0])
  37.  
  38. imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  39. ret, thresh = cv2.threshold(imgray,20,255,3)
  40. contours, hierarchy = cv2.findContours(thresh, 1, 2)
  41. cnt = contours[0]
  42. x,y,w,h = cv2.boundingRect(cnt)
  43.  
  44. print(x)
  45. print(y)
  46. print(w)
  47. print(h)
  48.  
  49. cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
  50.  
  51. plt.imshow(img),plt.colorbar(),plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement