Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crop black edges with OpenCV

I think it should be a very simple problem, but I cannot find a solution or an effective keyword for search.

I just have this image.

the original image

The black edges are useless so that I want to cut them, only leaving the Windows icon (and the blue background).

I do not want to calculate the coordinate and the size of the Windows icon. GIMP and Photoshop have sort of autocrop function. OpenCV does not have one?

like image 580
Gqqnbig Avatar asked Nov 24 '12 05:11

Gqqnbig


People also ask

How do I crop in OpenCV?

There is no specific function for cropping using OpenCV, NumPy array slicing is what does the job. Every image that is read in, gets stored in a 2D array (for each color channel). Simply specify the height and width (in pixels) of the area to be cropped. And it's done!

How do I make a Colour into grayscale using OpenCV?

cvtColor() method with cv2. COLOR_BGR2GRAY as a parameter to convert it into gray-scale.

How do you crop an image with coordinates in Python?

crop() function that crops a rectangular part of the image. top and left : These parameters represent the top left coordinates i.e (x,y) = (left, top). bottom and right : These parameters represent the bottom right coordinates i.e. (x,y) = (right, bottom).


2 Answers

I am not sure whether all your images are like this. But for this image, below is a simple python-opencv code to crop it.

first import libraries :

import cv2 import numpy as np 

Read the image, convert it into grayscale, and make in binary image for threshold value of 1.

img = cv2.imread('sofwin.png') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) _,thresh = cv2.threshold(gray,1,255,cv2.THRESH_BINARY) 

Now find contours in it. There will be only one object, so find bounding rectangle for it.

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnt = contours[0] x,y,w,h = cv2.boundingRect(cnt) 

Now crop the image, and save it into another file.

crop = img[y:y+h,x:x+w] cv2.imwrite('sofwinres.png',crop) 

Below is the result :

enter image description here

like image 138
Abid Rahman K Avatar answered Oct 07 '22 20:10

Abid Rahman K


import numpy as np  def autocrop(image, threshold=0):     """Crops any edges below or equal to threshold      Crops blank image to 1x1.      Returns cropped image.      """     if len(image.shape) == 3:         flatImage = np.max(image, 2)     else:         flatImage = image     assert len(flatImage.shape) == 2      rows = np.where(np.max(flatImage, 0) > threshold)[0]     if rows.size:         cols = np.where(np.max(flatImage, 1) > threshold)[0]         image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]     else:         image = image[:1, :1]      return image 
like image 31
fviktor Avatar answered Oct 07 '22 22:10

fviktor