Saravanan666/pypi-org huggingface dataset:
Package: cv2-collage-v2
Creates a collage from images with OpenCVpip install cv2-collage-v2Tested against Windows 10 / Python 3.10 / AnacondaHow to use itfromcv2_collage_v2importcreate_collage_v2importosimportcv2folder=r'C:\Users\hansc\Downloads\bd'allpics=[]forfinos.listdir(folder):try:allpics.append(cv2.imread(os.path.join(folder,f)))exceptExceptionasfe:print(fe)continuecollage=create_collage_v2(allpics,maxwidth=1500,heightdiv=16,widthdiv=5,background=(0,0,0),save_path='e:\\nyhctest.png',)cv2.imshow('Collage',collage)cv2.waitKey(0)cv2.destroyAllWindows()Args:lst(list|tuple):Alistortupleofimages-allowed:[filepaths,base64,bytes,PIL,urls,np.array].maxwidth(int,optional):Themaximumwidthofthecollage.Defaultsto1080.heightdiv(int,optional):Theheightdivisionfactor.Defaultsto6.widthdiv(int,optional):Thewidthdivisionfactor.Defaultsto2.background(tuple,optional):Thebackgroundcolorofthecollage.Defaultsto(0,0,0).save_path(str|None,optional):Thefilepathtosavethecollage.DefaultstoNone.Returns:np.array:ANumPyarrayrepresentingthecollageimage.
Package: cv2-enumerate-cameras
cv2_enumerate_camerasInstallationInstall from PyPIpip install cv2_enumerate_camerasInstall from Sourcepip install git+https://github.com/chinaheyu/cv2_enumerate_cameras.gitExampleRun as Scriptpython -m cv2_enumerate_camerasCamera InfoThecv2_enumerate_cameras.enumerate_cameras()function will return a list ofCameraInfoobjects.CameraInfo.index: Camera index for creatingcv2.VideoCaptureCameraInfo.name: Camera nameCameraInfo.path:  Camera device pathCameraInfo.vid:  Vendor identifierCameraInfo.pid:  Product identifierEnumerate Camerasimportcv2fromsrc.cv2_enumerate_camerasimportenumerate_camerasforcamera_infoinenumerate_cameras(cv2.CAP_MSMF):print(f'{camera_info.index}:{camera_info.name}')Output:0: HD Webcam
...Find Camera by Vendor and Product Identifierimportcv2fromsrc.cv2_enumerate_camerasimportenumerate_camerasdeffind_camera(vid,pid,apiPreference=cv2.CAP_MSMF):foriinenumerate_cameras(apiPreference):ifi.vid==vidandi.pid==pid:returncv2.VideoCapture(i.index,apiPreference)returnNonecap=find_camera(0x04F2,0xB711)whileTrue:result,frame=cap.read()ifnotresult:breakcv2.imshow('frame',frame)ifcv2.waitKey(1)==ord('q'):breakTODOWindows SupportLinux SupportMacOS Support
Package: cv2-extras
# OpenCV Extras
cv2-extras (cv2x) is a Python library for higher level functions used in image
analysis and computer vision. OpenCV is an incredible library for building
image analysis pipelines, but sometimes feels quite low-level, and it should
stay that way. However, for those times when the lazy programmer finds
themselves writing the same lines over and over or when there is just something
too useful to keep to yourself…there’s cv2x.Feel free to submit pull requests if some repetitive task is bugging you.## UsageRecommended import convention:import cv2_extras as cv2xFunctions:fill_holes(mask)filter_contours_by_size(mask, min_size=1024, max_size=None)find_border_contours(contours, img_h, img_w)fill_border_contour(contour, img_shape)find_border_by_mask(signal_mask,contour_mask,
max_dilate_percentage=0.2,
dilate_iterations=1)find_contour_union(contour_list, img_shape)generate_background_contours(hsv_img,non_bg_contours,
remove_border_contours=True,
plot=False)elongate_contour(contour, img_shape, extend_length)calculate_nonuniform_field(single_channel)correct_nonuniformity(single_channel, mask=None)color_transfer(ref_img, target_img, clip=True, preserve_paper=True)
Package: cv2-fit-text-in-box
Finds the best fitting text size for a bounding box# Tested with:# Python 3.9.13# Windows 10pipinstallcv2-fit-text-in-boxfromcv2_fit_text_in_boximportfit_text_in_boxtext="""Eins, zwei, drei, vier, fünf,sechs, sieben, acht, neun, aus!Alle warten auf das Licht.Fürchtet euch, fürchtet euch nicht!Die Sonne scheint mir aus den Augen,sie wird heut Nacht nicht untergehen,und die Welt zählt laut bis zehn.Eins, hier kommt die Sonne.Zwei, hier kommt die Sonne.Drei, sie ist der hellste Stern von allen.Vier, hier kommt die Sonne.Die Sonne scheint mir aus den Händen,kann verbrennen, kann euch blenden,wenn sie aus den Fäusten bricht,legt sich heiß auf dein Gesicht,legt sich schmerzend auf die Brust,das Gleichgewicht wird zum Verlust,lässt dich hart zu Boden gehen,und die Welt zählt laut bis zehn.Eins, hier kommt die Sonne.Zwei, hier kommt die Sonne.Drei, sie ist der hellste Stern von allen,vier, und wird nie vom Himmel fallen.Fünf, hier kommt die Sonne.Sechs, hier kommt die Sonne.Sieben, sie ist der hellste Stern von allen.Acht, neun, hier kommt die Sonne."""fertig=fit_text_in_box(text,textcolor=[(255,255,0),(0,0,0)],backgroundcolor=[(0,0,150),(0,110,0)],transparent=True,filepath="f:\\testpicture1.png",maximalx=1280,maximaly=420,columns=2,fontart="arial.ttf",fontborder=2,distance_upper_left=(1,1),)fertig=fit_text_in_box(text,textcolor=[(255,0,0)],backgroundcolor=[(50,50,0),(30,30,0),(10,0,0)],transparent=False,filepath="f:\\testpicture3.png",maximalx=720,maximaly=720,columns=1,fontart="arial.ttf",fontborder=2,distance_upper_left=(1,1),)fertig=fit_text_in_box(text,textcolor=[(255,255,0)],backgroundcolor=[(0,0,150),(0,0,0)],transparent=True,filepath="f:\\testpicture4.png",maximalx=1280,maximaly=720,columns=3,fontart="arial.ttf",fontborder=2,distance_upper_left=(1,1),)
Package: cv2imageload
cv2ImageLoadpython cv2通过图片文件、图片url、图片的base64编码加载图片。cv2ImageLoad安装pip install cv2imageload使用from cv2imageload import ImageLoad, ImageLoadError

file = 'th-108.jpg'
url = 'http://*.com/test.png'
base64_str = '图片的base64编码字符串'

# 加载图片文件
try:
    image = ImageLoad.loadImage(file)
except ImageLoadError as e:
    print(e.reason)

# 加载url图片
try:
    image = ImageLoad.loadImage(url)
except ImageLoadError as e:
    print(e.reason)

# 加载base64编码的图片
try:
    image = ImageLoad.loadImage(base64_str)
except ImageLoadError as e:
    print(e.reason)

# 将图片编码为base64字符串
try:
    base64_str = ImageLoad.base64EncodeImage(image, with_base64_header=True, file_ext='jpg')
except ImageLoadError as error:
    print(error.reason)
print(base64_str[:30])
Package: cv2imshow
cv2.imshow without freezing - Windows onlyTested against Windows 10 / Python 3.10 / Anacondapip install cv2imshowThis module provides a solution for the freezing issue encountered when updating images using OpenCV's cv2.imshow function
By addressing the freezing issue and providing non-blocking image display, this module enables smoother real-time image visualization
in OpenCV applications and allows for improved user experience when working with image processing and computer vision tasks.Non-blocking image display:The module enables displaying images without freezing the execution of the program.
It utilizes subprocess to offload the image display to a separate process,
allowing the main program to continue running smoothly.Multi-process support:The module supports displaying images in a multi-process environment,
where multiple images can be shown simultaneously in separate windows without
interfering with each other or causing freezing issues.
(Important: each window has to have a different title and a different combination for killkeys)Keyboard control:The module provides an option to define a key combination that can be used to toggle the image display on and off.
This allows for convenient control of image visualization during program execution.
When the specified kill shortcut is triggered, the module gracefully terminates the image display process,
freeing system resources and ensuring a clean exit. This allows for easy and controlled termination
of the image display functionality without causing any disruption or instability in the main program.Memory efficiency:The module utilizes a queue-based mechanism to pass images between processes,
ensuring efficient memory usage even when displaying large images or
multiple images simultaneously.How to use itfromadbblitzimportAdbShotTCPfromkthread_sleepimportsleepfromcv2imshow.cv2imshowimportcv2_imshow_single,cv2_imshow_multiimportnumpyasnpshosho2=AdbShotTCP(device_serial="localhost:5555",adb_path=r"C:\ProgramData\chocolatey\lib\scrcpy\tools\scrcpy-win64-v2.0\adb.exe",ip="127.0.0.1",port=5555,max_frame_rate=60,max_video_width=960,scrcpy_server_version="2.0",forward_port=None,frame_buffer=24,byte_package_size=131072,sleep_after_exception=0.01,log_level="info",lock_video_orientation=0,)bi=shosho2.get_one_screenshot()cv2_imshow_single(title="pic2",image=bi.copy(),killkeys="ctrl+alt+q",# kills imshow)sleep(0.02)withAdbShotTCP(device_serial="localhost:5555",adb_path=r"C:\ProgramData\chocolatey\lib\scrcpy\tools\scrcpy-win64-v2.0\adb.exe",ip="127.0.0.1",port=5555,max_frame_rate=60,max_video_width=960,scrcpy_server_version="2.0",forward_port=None,frame_buffer=24,byte_package_size=131072,sleep_after_exception=0.01,log_level="info",lock_video_orientation=0,)asshosho:forbiinshosho:ifbi.dtype==np.uint16:continuecv2_imshow_multi(title="pic3",image=bi,killkeys="ctrl+alt+h",# switch on/off)sleep(0.001)
Package: cv2multilinewrite
cv2.putText with new linesTested against Windows 10 / Python 3.11 / Anacondapip install cv2multilinewriteCode from:https://stackoverflow.com/a/73471951/15096247importcv2importnumpyasnpimage=200*np.ones((550,410,3),dtype=np.uint8)image=add_text_to_image(image,"New line\nDouble new line\n\nLine too longggggggggggggggggggggg",top_left_xy=(0,10),)image=add_text_to_image(image,"Different font scale",font_scale=0.5,font_color_rgb=(0,255,0),top_left_xy=(0,150),)image=add_text_to_image(image,"New line with bg\nDouble new line\n\nLine too longggggggggggggggggggggg",bg_color_rgb=(255,255,255),font_color_rgb=(255,0,0),top_left_xy=(0,200),)image=add_text_to_image(image,"Different line specing,\noutline and font face",font_color_rgb=(0,255,255),outline_color_rgb=(0,0,0),top_left_xy=(0,350),line_spacing=1.5,font_face=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,)importmatplotlib.pyplotaspltplt.imshow(image)plt.show()
Package: cv2-multistack
Multiple image stack with cv2 (calculates height/width)# Tested with:# Python 3.9.13# Windows 10pipinstallcv2-multistackfromcv2_multistackimporthstack_multiple_pics,vstack_multiple_pics# Allowed image formats: url/path/buffer/base64/PIL/nplistofpics=["""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000008.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000009.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000010.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000011.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000012.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000013.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000014.png""","""https://raw.githubusercontent.com/hansalemaos/screenshots/main/cv2_putTrueTypeText_000015.png""",]bibi1=hstack_multiple_pics(listofpics,height=100,channels=3)bibi2=vstack_multiple_pics(listofpics,width=100,channels=3)
Package: cv2multizoom
Fast multiple zooms on a picture using cv2 and ffmpeg# Allowed image formats: url/path/buffer/base64/PIL/np# ffmpeg must be installedfromcv2multizoomimportmultizoommultizoom(img=r"https://github.com/hansalemaos/screenshots/raw/main/splitted1.png",howmanyzooms=10,# number of output pictures might be a little less than howmanyzoomsoutputfolder=r"F:\cv2mergepics\tt4",# will be created if it does not existzoomfactor_start=1,zoom_speed=2.5,framerate=29.97,zfill=7,# 0000001.png instead of 1.pngprefix="zoompics_",threads=5,)
Package: cv2obs
OpenCV Images (NumPy Arrays) to OBS Virtual CamTested against Windows 10 / Python 3.10 / Anacondapip install cv2obsExamplefromadbblitzimportAdbShotTCPfromkthread_sleepimportsleepimportnumpyasnpfromcv2obs.cv2obscamimportstart_cv2obs,get_index_of_working_camerascameras=get_index_of_working_cameras()px=start_cv2obs(height=540,width=960,fps=29.97,camera=cameras[-1],killkeys="ctrl+alt+l",)withAdbShotTCP(device_serial="localhost:5555",adb_path=r"C:\ProgramData\chocolatey\lib\scrcpy\tools\scrcpy-win64-v2.0\adb.exe",ip="127.0.0.1",port=5555,max_frame_rate=60,max_video_width=960,scrcpy_server_version="2.0",forward_port=None,frame_buffer=24,byte_package_size=131072,sleep_after_exception=0.01,log_level="info",lock_video_orientation=0,)asshosho:forbiinshosho:ifbi.dtype==np.uint16:continuepx.write_image(bi)# Writes images to the camera, image will be resized automatically# (according to width/height in start_cv2obs)sleep(0.001)get_index_of_working_cameras():"""Get the indices of the working cameras.Returns:List[int]: A list containing the indices of the cameras that are working.Note:- This function internally calls the `list_ports` function to test the camera ports.- The `list_ports` function returns a tuple with available ports, working ports, and non-working ports.- Only the working ports are extracted and returned by this function."""start_cv2obs(height:int=540,width:int=960,fps:int|float=29.97,camera:int=2,killkeys:str="ctrl+alt+l",):"""Start the cv2obs subprocess for capturing and processing camera images.Args:height (int): The desired height of the captured images. Defaults to 540.width (int): The desired width of the captured images. Defaults to 960.fps (int|float): The frames per second for capturing images. Defaults to 29.97.camera (int): The index of the camera to use. Defaults to 2.killkeys (str): The key combination to stop the cv2obs subprocess. Defaults to "ctrl+alt+l".Note:- The function internally creates a numpy array of shape (height, width, 3) with white pixels (255, 255, 255).- The numpy array is then encoded using `encode_var` function from the `varpickler` module.- The encoded array size is used for configuring the `bytesize` parameter of the `start_subprocess` function.- The cv2obs subprocess is started using the `start_subprocess` function with appropriate parameters.- The `px.write_image` attribute of the subprocess is set to a partial function `_write_image` for writing images."""
Package: cv2operator
cv2operatorcv2operator is a simple library to input various shapes like polygon rectangle and so on.FeaturesLineOperator: input a line by mouse dragginPolylineOperator: input a polyline by clickPolygonOperator: input a polygon by clickRectOperator: input a rectangle by dragginBrushOperator: paint mask region by dragginKeyOperator: key managementUsageHere is a simple example.import cv2
from cv2operator import KeyOperator, OperartorWindow, LineOperator

def line_cb(p1, p2):
    print(f"line: p1={p1}, p2={p2}")

image = cv2.imread("goru.jpg")
window = OperartorWindow("example", image)

line_op = LineOperator(window, callback=line_cb)

key_op = KeyOperator()
print(key_op.help())
key_op.main_loop()Operatorsall operators are used in a example code.
seedemo.pyinexamples.RectOperatorLineOperatorPolylineOperatorPolygonOperatorBrushOperator
Package: cv2pencil
Converts images to pencil sketches$pipinstallcv2pencilfromcv2pencilimportget_pencil_drawing# Allowed image formats: url/path/buffer/base64/PIL/np# save_diff / save_norm are optionala,b=get_pencil_drawing(r"https://raw.githubusercontent.com/hansalemaos/screenshots/main/merg1.png",dilate=(9,9),blur=7,save_diff="f:\\pencildrawing\\diff.png",save_norm="f:\\pencildrawing\\norm.png",)
Package: cv2-plt-imshow
cv2_plt_imshowUsing matplotlib_imshow for images read by cv2IntroductionOne of the major issue faced while usingcv2, especially when you are usingjupyter-notebooks, is to performcv2.imshowthe kernel breaks. Apart from this, most of the users are comfortable using matplotlib for display, specially its display in notebook using%matplotlib inlinemagic.This package provides two of the main function, converting the image to a format more suitable in matplotlib, and plotting the image using matplotlib in the notebooks.Table of contentsSetupUsageDependenciesContactSetuppip install cv2_plt_imshowUsageimport cv2
import matplotlib.pyplot as plt
from cv2_plt_imshow import cv2_plt_imshow, plt_format

# read image
im1 = cv2.imread('./images/potrait.jpg')

# use cv2_plt_imshow function to plot any image that was read by cv2, but is plotted using pyplot
cv2_plt_imshow(im1)

# Convert the image to be suitable for pyplot format and later use it for plotting using pyplot functions
im2 = cv2.imread('./images/landscape.jpg')
fig, axs = plt.subplots(2 , figsize=(20,20))
fig.suptitle('Vertically stacked subplots')
axs[0].imshow(plt_format(im1))
axs[1].imshow(plt_format(im2))Dependenciesmatplotlibcv2ContactAuthorGithub
Package: cv2PySide6
Python package which combinesOpenCV-PythonandPySide6.IntroductionPySide6provides powerful tools to acquire video stream from file or device, and to display it on GUI.cv2is a de facto standard module for image analysis with Python.
It is natural to process the image withcv2and display it usingPySide6.cv2PySide6is a package to help build the video frame pipeline for this purpose.
It provides the object to convertPySide6.QVideoFrametonumpy.ndarray, and widget to directly display the array.InstallationBefore you install, be careful for other Qt-dependent packages installed in your environment.
For example, non-headlessOpenCV-Pythonmodifies the Qt dependency thus makingPySide6unavailable.cv2PySide6can be installed usingpip.$ pip install cv2PySide6How to useUser can construct a pipeline which convertsQVideoFrametondarray, performs any desired processing and displays to the widget.Video display pipelineQVideoFrametondarrayQVideoFrameis acquired from media file (PySide6.QMediaPlayer) or camera capture session (PySide6.QMediaCaptureSession) by settingPySide6.QVideoSinkto them and listening toQVideoSink.videoFrameChangedsignal.To convert it, pass the video framecv2PySide6.FrameToArrayConverterand listen toFrameToArrayConverter.arrayChangedsignal.(Note) If you want to convert a singlePySide6.QImagetondarray,qimage2ndarraypackage provides handy functions.Displayingndarraycv2PySide6.NDArrayLabelis a widget to directly displayndarray.
It can also scale the image with respect to the widget size, and user can select the scaling mode.Convenience classesFor convenience,cv2PySide6providesNDArrayVideoPlayerandNDArrayMediaCaptureSessionwhich inherits theirPySide6counterparts and emitsarrayChangedsignal.NDArrayVideoPlayerWidgetandNDArrayCameraWidgetare the minimal implementation to display the video stream with them.However, time-consuming image processing will block the GUI with these classes because they use a single thread.
To build multithread pipeline, refer to the examples and build the pipeline yourself.ExamplesUse cases with multithreading are provided inexamplesdirectory.
They can be found in documentation as well.DocumentationDocumentation can be found on Read the Docs:https://cv2pyside6.readthedocs.io/If you want to build the document yourself, clone the source code and install with[doc]option.
Go todocdirectory and build.$ pip install cv2PySide6[doc]
$ cd doc
$ make html
Package: cv2-rectangle-around-center
Creates a rectangle around a center point$pipinstallcv2-rectangle-around-centerfromcv2_rectangle_around_centerimportline_rectangle_center,rectangle_center# Allowed image formats: url/path/buffer/base64/PIL/npim1=line_rectangle_center(image=r"https://raw.githubusercontent.com/hansalemaos/screenshots/main/diff.png",center=(150,150),width=200,height=280,thickness=6,color1=(255,0,0),color2=(255,255,0),color3=(255,0,255),color4=(0,255,255),save_path="f:\\recta\\lines.png",)im2=rectangle_center(image=r"https://raw.githubusercontent.com/hansalemaos/screenshots/main/diff.png",center=(150,150),width=200,height=280,thickness=6,color=(255,0,0),save_path="f:\\recta\\rect1.png",)im3=rectangle_center(image=r"https://raw.githubusercontent.com/hansalemaos/screenshots/main/diff.png",center=(150,150),width=200,height=280,thickness=-1,color=(255,255,0),save_path="f:\\recta\\rect2.png",)
Package: cv2routine
CV2-RoutineThis package makes some routine operations in OpenCV easier. Also this project is used for learning, so do not use it in serious projects, as it is impossible to guarantee the performance of this packageCurrent status:In developmentDocumentationDocumentation is availablehere(WIP. Will be ready in a while)Installationpipinstallcv2routineUsageFor the complete packageimportcv2routineascv2rFor a specific modulefromcv2routineimporttransformastfDependenciesOpenCV
Package: cv2-stack-images
Stacks 2 images (horizontal/vertical)$pipinstallcv2-stack-imagesfromcv2_stack_imagesimportconcat2images# Allowed image formats: url/path/buffer/base64/PIL/np# You must pass either width or height, but not both!# save_path is optionalb1=concat2images(img1=r"https://github.com/hansalemaos/screenshots/raw/main/colorfind3.png",img2=r"https://github.com/hansalemaos/screenshots/raw/main/pic4.png",width=300,save_path="f:\\concatimg\\vertical.png",)b2=concat2images(img1=r"https://github.com/hansalemaos/screenshots/raw/main/colorfind3.png",img2=r"https://github.com/hansalemaos/screenshots/raw/main/pic4.png",height=300,save_path="f:\\concatimg\\horizontal.png",)
Package: cv2studio
cv2studiocv2studiois an OpenCV framework that give
you an ability to decompose processing flow into
components.FeaturesComponent-based developmentChannel independenceClasses wrappers for HighGUI elements of OpenCVChannel independence for componentsGetting StartedThe main principle behind this framework is decomposition.
Splitting up a code into one-format components make
it highly reusable. It becomes easy to develop
different parts of video/image processing separately and
share it with others.InstallingTo install the latest release:pipinstallcv2studioUsageImportingBefore using features of the framework
goes importing.from cv2studio import App, ComponentComponent creationTo create a component describe a class derived fromComponent.
To use this class it's required to declare the methodprocess(self, img),
whereimgis an image to be process. This function must return an image as well.classBlur(Component):defprocess(self,img):img=cv2.GaussianBlur(img,(5,5),5)returnimgThis component apply blur to an input image.App creationTo create an app that will hold processing components
describe a class derived from 'App' and add components
usingadd_component(component)method.classVideoApp(App):def__init__(self,path):App.__init__(self,path,VIDEO)# self.add_component(MyComponent())self.add_component(Blur())RunningTo run the described app usemain_loopmethod.
It will start main processing loop with applying
chain of added component.app=VideoApp('path/to/video')app.main_loop()main_loopstarts a video processing loop. For creating
more complex app see the following examples.TestingTo run tests run the following command:pytestVersioningWe use SemVer for versioning. For the versions available,
see the tags on this repository.ContributingPlease read CONTRIBUTE.md for details on our code of conduct, and the process for submitting pull requests to us.LicenseThis project is licensed under the MIT License - see theLICENSE.mdfile for details
Package: cv2utils
Implementation of some object detection in Python3.5+. It is included in this project:Face and Eye detection using OpenCV Haar feature-based cascade classifiers.Face detection using OpenCV Deep Neural NetworksFor for info,Read the docs.InstallationIt can be installed through pip:pip3install--usercv2utilsThis implementation requires OpenCV and Numpy.ReferencesOpenCV HaarCascadesOpenCV DnnLicenseMIT