OpenCV Image Processing - Crop an image to a circle

Source: Internet
Author: User
Keywords Cloud Computing OpenCV Image Cropped to Round
1, demand

In order to facilitate the display of user avatars on the front of the project, the avatar needs to be processed as a circle and the non-circular area as transparent. In fact, the front-end can be displayed at the time of processing, but the front-end with WebGL, temporarily uncertain, so the image from the back-end one-time processing.
So, we try to use the Linux tool Convert to complete, however, there is no solution, the subsequent decision to use Python + OpenCV.

2, to achieve

Excellent code does not need to explain, look at the code directly, O (∩ _ ∩) O.

#coding: utf8 import numpy as np import cv2 from matplotlib import pyplot as plt import glob as gb # image processing, access to the largest inscribed circle of the picture, the other area set to transparent def img_deal (input_img): # cv2.IMREAD_COLOR, read BGR Channel value, the color channel, this parameter is the function default value # cv2.IMREAD_UNCHANGED, read the alpha channel value # cv2.IMREAD_ANYDEPTH, read the gray map, the return matrix is ​​two-dimensional img = cv2.imread (input_img, cv2.IMREAD_UNCHANGED) rows, cols, channel = img.shape # Create a 4-channel new image, including transparent channels, the initialization is transparent img_new = np.zeros ((rows, cols, 4), np.uint8) img_new [:,:, 0: 3] = img [:,:, 0: 3] # Create a single-channel image, set the maximum inscribed circle to opaque, note the coordinates of the center of the circle, cols is the x coordinate, rows is The y coordinates are: img_circle = np.zeros ((rows, cols, 1), np.uint8) img_circle [:,:,:]] = 0 # Set to full transparency img_circle = cv2.circle (img_circle, (cols / 2, rows / 2), min (rows, cols) / 2, (255), - 1) # set the maximum inscribed circle opaque # image fusion img_new #: Cv2.imencode ('. Jpg', img) [1] .tofile (',': ', 0] # img_circle [:,:, 0] # save the image cv2.imwrite (input_img + ". Png", img_new) ./9.jpg ') # Save to another location # Display pictures, call opencv Show # cv2.imshow ("img_new", img_new) # cv2.waitKey (0) # cv2.destroyAllWindows () # Display pictures, call matplotlib .pyplot Show plt.subplot (121), plt.imshow (img_convert (img), cmap = 'gray'), plt.title ('IMG') plt.subplot (122), plt.imshow (img_convert (img_new), plt.title ('IMG_NEW') plt.show () # cv2 Image conversion with matplotlib, cv2 is bgr format, matplotlib is rgb format def img_convert (cv2_img): # grayscale image directly returns if len (cv2_img.shape) == 2: return cv2_img # 3 channel BGR picture elif len (cv2_img.shape) == 3 and cv2_img.shape [2] == 3: b, g, r = cv2.split (cv2_img ) return cv2.merge ((r, g, b)) # 4 Channel BGR picture elif len (cv2_img.shape) == 3 and cv2_img.shape [2] == 4: b, g, r, a = cv2 .split (cv2_img) return cv2.merge ((r, g, b, a)) # unknown image format else: return cv2_img # main function if __name__ == "__main__": img_path = gb.glob ("img / *") for path in img_path: print path img_deal (path) 3, Effect

4, Reference Help Documents OpenCV complete sets of information is relatively small, you also need to see help documentation >>> >>> from matplotlib import pyplot Backend TkAgg is interactive backend. function imshow in module matplotlib.pyplot: imshow (X, cmap = None, norm = None, aspect = None, interpolation = None, alpha = None, vmin = None, vmax = None, origin = None, extent = None, None, filradorm = 1, filterrad = 4.0, imlim = None, resample = None, url = None, hold = None, ** kwargs) call signature :: imshow (X, cmap = None, interpolation = None, alpha = None, vmin = None, vmax = None, origin = None, extent = None, ** kwargs) Display the image in * X * to current axes. * X * may be a float array, a uint8 array or a PIL image. If * X * is an array, * X * can have the following shapes: * MxN - luminance (grayscale, float array only) * MxNx3 - RGB (float or uint8 array) * MxNx4 - RGBA (float or uint8 array) The value for each component of MxNx3 and MxNx4 float arrays should be in the range 0.0 to 1.0; MxN float arrays may be normalized. An: class: `matplotlib.image.AxesImage` instance is returned.
Related Article

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.