Load, crop, and save an image with OpenCV 3 and Python 3 on Raspberry Pi 2

Michael Jordan was one of the greatest athletes in the world. He was the best NBA player in his era. This legendary picture shows how he tormented Utah Jazz during his 1998 NBA Final game with the Chicago Bulls with his phenomenal ‘last shot’. But, what would happen if he actually missed the shot of his final career with the Bulls? The crowd would’ve gone…. “BOOOOO!!! AIR BALL!”

History may not change, but evidence supporting it may be altered with OpenCV3 and Python 3.

Jordan’ original last shot

jordan-lastshot

Jordan’s air ball

jordan-airball

And here is the nasty code that changed history. Well, at least history from the point-of-view of the above picture altered using less than 20 lines of Python 3 codes utilising OpenCV3 cv2 library.

Pseudocode:

  • define filenames
  • read original name
  • show original file
  • crop  a background patch and store it in ‘replacement’ variable
  • crop the ball and store it in ‘ball’ variable
  • replace an ROI with the ball crop
  • replace the ball ROI with the background patch
  • save the edited image
  • show the edited image
  • close viewer when button clicked

Python 3 code:


import cv2
import numpy as np

#my first openCV python3 file
#simple image editor which will load, modify and save image.

ori_filename = 'jordan-lastshot.jpg'
new_filename = 'jordan-airball.jpg'

print("Reading and displaying file: ", ori_filename)
ori_img = cv2.imread(ori_filename)
cv2.imshow(ori_filename,ori_img)

print("Modifying file")
new_img = ori_img
replacement = new_img[280:330, 330:380]
ball = new_img[183:223, 525:565]

new_img[363:403, 575:615] = ball
new_img[183:233, 525:575] = replacement

print("Displaying modified file: " , new_filename)
cv2.imwrite(new_filename, new_img)
cv2.imshow(new_filename,new_img)

cv2.waitKey(0)
cv2.destroyAllWindows()

Diclaimer: Image is copyright of its owner www.nba.com. We just borrowed it for this exercise. No airball actually happened and Jordan was the final MVP as well as the winner of the series in 1998 with the Bulls.

(Visited 14,107 times, 1 visits today)