A
A
Artem2017-07-08 23:08:54
Python
Artem, 2017-07-08 23:08:54

Python How to crop images?

Hi all!
dc6a0b9f3e144038813f2dbb64be2684.jpg3ef2b308c0f94d10914cedd312cf3ba5.jpgc7bc2f332ee04ed9882c5b9eecf4e562.jpg
Help, please, with one problem - I have a collection of pictures (size 550 * 500), such as: leave only the white frame and the picture itself. The question is - is it possible to do this, given that the boundaries of this white frame change from time to time (as in the second picture for example)? Those. there is no way to empirically pick up the borders of the image and just crop it through PIL.Image.crop () ...
I would be grateful for any advice on how to proceed ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2017-07-11
@Malodar

I will supplement the answer of Aleksey Solovyev .
1. Convert to bw.
2. On a binary image (instead of cv2.Canny, you need to use cv2.threshold, since the color of the frame is white, it will not be difficult to choose the threshold) you need to find the outer contour (cv2.findContours with the RETR_EXTERNAL parameter) and then it remains to save the part of the image that lies inside contour.

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>

int main(int argc, char *argv[])
{
  cv::Mat img,gr,th;
  img = cv::imread("1.jpg");
  cv::cvtColor(img, gr, cv::COLOR_BGR2GRAY);
  
  cv::threshold(gr, th, 240.0, 255, cv::THRESH_BINARY);

  std::vector<std::vector<cv::Point> > contours;
  cv::findContours(th, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

  auto max_vector_comp = [](std::vector<cv::Point> &lhs,
    std::vector<cv::Point> &rhs)
  {
    return lhs.size() < rhs.size();
  };
  //поиск самого длинного контура
  auto maxVector = std::max_element(contours.begin(), contours.end(),
    max_vector_comp);
  //находим описывающий прямоугольник
  cv::Rect roi = cv::boundingRect(*maxVector);

  cv::Mat croppedImg;
  croppedImg = img(roi);
  cv::imshow("inImg", img);
  cv::imshow("croppedImg", croppedImg);
  cv::waitKey();
  return 0;
}

P
Python Beginner, 2017-07-09
@Pythonpy

Opencv to the rescue.
The scanning window works from the top left pixel.
The image is a 2D matrix x*y.
We are looking for the first line with a white pixel.
Cut off the lines at the top.
Now we do the same thing, but only in the opposite direction, and start the scanning window from the end.
We cut the side gray walls in columns.
I don’t know how effective it is, but this is the first solution that came to mind.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question