Binarization with OpenCV / Python


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2
import time

def conv():
	#Threshold setting
	threshold = 100

	#Binarization(The number of pixels exceeding the threshold value of 100 is set to 255.)
	ret, img_thresh = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)

	#Display of binarized image
	cv2.imshow("img_th", img_thresh)
	cv2.waitKey()
	cv2.destroyAllWindows()

def fps(video):
	fps = video.get(cv2.CAP_PROP_FPS)
	print("FPS settings, video.get(cv2.CAP_PROP_FPS) : {0}".format(fps))
	
	#Number of frames to get
	num_frames = 120
	
	print("Acquiring{0} frames".format(num_frames))
	
	#Start time
	start = time.time()
	
	#Get the frame
	#for i in range(0, num_frames):
	#	ret, frame = video.read()
	
	#ending time
	end = time.time()
	
	# Time elapsed
	seconds = end - start
	print("elapsed time: {0} seconds".format(seconds))
	
	# Calculate frames per second
	fps = num_frames / seconds
	print("Calculated FPS: {0}".format(fps))

class FPS:
	def __init__(self):
		self.flag = False
		self.start = 0
		self.end = 0
		self.fps = 0
		self.framecnt = 0
			
	def calc_fps(self):
		if self.flag == False:
			self.start = time.time()
			self.flag = True		
		else:
			diff = time.time() - self.start
			if diff > 1.0:
				self.fps = self.framecnt / diff
				self.framecnt = 0
				self.start =  time.time()

		self.framecnt += 1
		return self.fps

def test1(mode):
	URL = "http://172.23.64.38:8081/?action=stream"
	winname ="winname"
	cv2.namedWindow(winname, cv2.WINDOW_NORMAL)

	try :
		if mode == 0:
			s_video = cv2.VideoCapture(0)
		else:
			s_video = cv2.VideoCapture(URL)


		#Threshold setting
		threshold = 200
		fpsobj = FPS()

		while True:
			
			start = time.time()
			end = time.time()

			seconds = end - start

			ret, srcimg = s_video.read()
			#cv2.imshow(winname,img)
			key = cv2.waitKey(1) & 0xff
			if key == ord('q'): break

			#Binarization(The number of pixels exceeding the threshold value of 100 is set to 255.)
			#cv2.threshold(image,Threshold,Thresholdを超えた場合に変更する値,Binarization method)
			ret, img = cv2.threshold(srcimg, threshold, 255, cv2.THRESH_BINARY)
			
			ksize=7 #Aperture size 3, 5,An odd number greater than 1 such as or 7. The larger the number, the more blurred.
			img = cv2.medianBlur(img,ksize)
						
			img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #Specify BGR2 ~ instead of RGB2 ~
			ret, img = cv2.threshold(img, 20, 255, cv2.THRESH_BINARY)


			#print("{}".format( fpsobj.calc_fps()))
			if ret:
				#Display of binarized image
				cv2.imshow(winname, img)
	except:
		pass

	cv2.destroyAllWindows()




if __name__ == "__main__":
	test1(1)

C++



#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <stdio.h>

#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/photo.hpp"

//    http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html

        Mat dst;
        int criteria = 100;
        int max = 255;


        for ( ;;) {

            cap.read( frame );
            cv::threshold( frame, dst, criteria, max, THRESH_BINARY );       // binalized


            int ksize = 7;// #Aperture size 3, 5,An odd number greater than 1 such as or 7. The larger the number, the more blurred.
            cv::medianBlur( dst, dst, ksize );

            cv::cvtColor( dst, dst, COLOR_BGR2GRAY );// #Specify BGR2 ~ instead of RGB2 ~
            cv::threshold( dst, dst, 20, max, THRESH_BINARY );
            

            imshow( "Live", dst );
            if ( waitKey( 5 ) >= 0 ) {
                break;
            }
        }
    


Recommended Posts

Binarization with OpenCV / Python
"Apple processing" with OpenCV3 + Python3
Image editing with python OpenCV
Camera capture with Python + OpenCV
[Python] Using OpenCV with Python (Basic)
Face detection with Python + OpenCV
Using OpenCV with Python @Mac
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Edge Detection)
Image processing with Python 100 knocks # 3 Binarization
Easy Python + OpenCV programming with Canopy
Try face recognition with python + OpenCV
Cut out face with Python + OpenCV
Face recognition with camera with opencv3 + python2.7
Load gif images with Python + OpenCV
Find image similarity with Python + OpenCV
Use OpenCV with Python 3 in Window
Draw an illustration with Python + OpenCV
Track baseball balls with Python + OpenCV
Graph Based Segmentation with Python + OpenCV
Draw arrows (vectors) with opencv / python
Basic study of OpenCV with Python
FizzBuzz with Python3
Scraping with Python
Statistics with python
Python2.7 + CentOS7 + OpenCV3
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
OpenCV Samples (Python)
Bingo with python
Zundokokiyoshi with python
[Note] openCV + python
Excel with Python
Microcomputer with Python
Cast with python
Face detection with Python + OpenCV (rotation invariant)
Save video frame by frame with Python OpenCV
Capturing images with Pupil, python and OpenCV
I tried non-photorealistic rendering with Python + opencv
Image processing with Python & OpenCV [Tone Curve]
Image acquisition from camera with Python + OpenCV
[python, openCV] base64 Face recognition with images
Create miscellaneous Photoshop videos with Python + OpenCV ③ Create miscellaneous Photoshop videos
[Python] Read images with OpenCV (for beginners)
Until you can use opencv with python
Light image processing with Python x OpenCV
Smoothing edge-saved with python + OpenCV (BilateralFilter, NLMeansFilter)
Serial communication with Python
Zip, unzip with python
Hello World and face detection with OpenCV 4.3 + Python
Primality test with Python
Python with eclipse + PyDev.