Converting an OpenCV Image to Black and White

Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings: 1. Read a grayscale image import cv2 im_gray = cv2.imread(‘grayscale_image.png’, cv2.IMREAD_GRAYSCALE) 2. Convert grayscale image to binary (thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) which determines the threshold automatically from the image using Otsu’s method, or if you … Read more

How can I get the position and draw rectangle using opencv?

So you have a problem unrelated to your question. However, you can achieve your goal using only OpenCV highgui facilites: #include <opencv2\opencv.hpp> #include <iostream> using namespace std; using namespace cv; vector<Rect> rects; bool bDraw; Rect r; Point base; Mat3b img; Mat3b layer; Mat3b working; void CallBackFunc(int event, int x, int y, int flags, void* userdata) … Read more

Error (-215) size.width>0 && size.height>0 occurred when attempting to display an image using OpenCV

“error: (-215)” means that an assertion failed. In this case, cv::imshow asserts that the given image is non-empty: https://github.com/opencv/opencv/blob/b0209ad7f742ecc22de2944cd12c2c9fed036f2f/modules/highgui/src/window.cpp#L281 As noted in the Getting Started with Images OpenCV Python tutorial, if the file does not exist, then cv2.imread() will return None; it does not raise an exception. Thus, the following code also results in the … Read more

Fast color quantization in OpenCV

There are many ways to quantize colors. Here I describe four. Uniform quantization Here we are using a color map with uniformly distributed colors, whether they exist in the image or not. In MATLAB-speak you would write qimg = round(img*(N/255))*(255/N); to quantize each channel into N levels (assuming the input is in the range [0,255]. … Read more