id stringlengths 6 6 | text stringlengths 20 17.2k | title stringclasses 1
value |
|---|---|---|
244072 | Laravel's pagination feature allows you to query a subset of data and provides your users with the ability to navigate between *pages* of those results.
Because Laravel's paginator was designed for static applications, in a non-Livewire app, each page navigation triggers a full browser visit to a new URL containing th... | |
244073 | ## Using cursor pagination
Livewire also supports using Laravel's cursor pagination — a faster pagination method useful in large datasets:
```php
public function render()
{
return view('show-posts', [
'posts' => Post::cursorPaginate(10),
]);
}
```
By using `cursorPaginate()` instead of `paginate()` o... | |
244076 | Livewire offers powerful support for uploading files within your components.
First, add the `WithFileUploads` trait to your component. Once this trait has been added to your component, you can use `wire:model` on file inputs as if they were any other input type and Livewire will take care of the rest.
Here's an examp... | |
244077 | ## Testing file uploads
You can use Laravel's existing file upload testing helpers to test file uploads.
Below is a complete example of testing the `UploadPhoto` component with Livewire:
```php
<?php
namespace Tests\Feature\Livewire;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use App... | |
244080 | ## Object schemas
When extending Livewire's JavaScript system, it's important to understand the different objects you might encounter.
Here is an exhaustive reference of each of Livewire's relevant internal properties.
As a reminder, the average Livewire user may never interact with these. Most of these objects are ... | |
244091 | Properties store and manage data inside your Livewire components. They are defined as public properties on component classes and can be accessed and modified on both the server and client-side.
## Initializing properties
You can set initial values for properties within your component's `mount()` method.
Consider the... | |
244092 | ## Supported property types
Livewire supports a limited set of property types because of its unique approach to managing component data between server requests.
Each property in a Livewire component is serialized or "dehydrated" into JSON between requests, then "hydrated" from JSON back into PHP for the next request.... | |
244093 | ## Security concerns
While Livewire properties are a powerful feature, there are a few security considerations that you should be aware of before using them.
In short, always treat public properties as user input — as if they were request input from a traditional endpoint. In light of this, it's essential to validate... | |
244104 | Livewire provides a simple `wire:click` directive for calling component methods (aka actions) when a user clicks a specific element on the page.
For example, given the `ShowInvoice` component below:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Invoice;
class ShowInvoice extends Compo... | |
244105 | ```blade
<form wire:submit="save">
<label>
<span>Title</span>
<input type="text" wire:model="title">
@error('title') <span>{{ $message }}</span> @enderror
</label>
<label>
<span>Title</span>
<input type="text" wire:model="title">
@error('title') <span>{{ ... | |
244106 | Livewire actions are methods on your component that can be triggered by frontend interactions like clicking a button or submitting a form. They provide the developer experience of being able to call a PHP method directly from the browser, allowing you to focus on the logic of your application without getting bogged dow... | |
244107 | vent listeners
Livewire supports a variety of event listeners, allowing you to respond to various types of user interactions:
| Listener | Description |
|-----------------|-------------------------------------------|
| `wire:click` | Triggered when an element is clicked |
... | |
244110 | ecurity concerns
Remember that any public method in your Livewire component can be called from the client-side, even without an associated `wire:click` handler that invokes it. In these scenarios, users can still trigger the action from the browser's DevTools.
Below are three examples of easy-to-miss vulnerabilities ... | |
244111 | Many modern web applications are built as "single page applications" (SPAs). In these applications, each page rendered by the application no longer requires a full browser page reload, avoiding the overhead of re-downloading JavaScript and CSS assets on every request.
The alternative to a *single page application* is ... | |
244112 | with analytics software
When navigating pages using `wire:navigate` in your app, any `<script>` tags in the `<head>` only evaluate when the page is initially loaded.
This creates a problem for analytics software such as [Fathom Analytics](https://usefathom.com/). These tools rely on a `<script>` snippet being evaluat... | |
244113 | File downloads in Livewire work much the same as in Laravel itself. Typically, you can use any Laravel download utility inside a Livewire component, and it should work as expected.
However, behind the scenes, file downloads are handled differently than in a standard Laravel application. When using Livewire, the file's... | |
244114 | When a Livewire component updates the browser's DOM, it does so in an intelligent way we call "morphing". The term _morph_ is in contrast with a word like _replace_.
Instead of _replacing_ a component's HTML with newly rendered HTML every time a component is updated, Livewire dynamically compares the current HTML with... | |
244115 | ## Automated upgrade tool
To save you time upgrading, we've included an Artisan command to automate as many parts of the upgrade process as possible.
After [installing Livewire version 3](/docs/upgrading#update-livewire-to-version-3), run the following command, and you will receive prompts to upgrade each breaking ch... | |
244116 | lpineJS
Livewire 3 ships with [AlpineJS](https://alpinejs.dev) by default.
If you manually include Alpine in your Livewire application, you will need to remove it, so that Livewire's built-in version doesn't conflict.
### Including Alpine via a script tag
If you include Alpine into your application via a script tag... | |
244120 | Livewire is a Laravel package, so you will need to have a Laravel application up and running before you can install and use Livewire. If you need help setting up a new Laravel application, please see the [official Laravel documentation](https://laravel.com/docs/installation).
To install Livewire, open your terminal an... | |
244126 | It's important to make sure your Livewire apps are secure and don't expose any application vulnerabilities. Livewire has internal security features to handle many cases, however, there are times when it's up to your application code to keep your components secure.
## Authorizing action parameters
Livewire actions are... | |
244127 | ## Middleware
When a Livewire component is loaded on a page containing route-level [Authorization Middleware](https://laravel.com/docs/authorization#via-middleware), like so:
```php
Route::get('/post/{post}', App\Livewire\UpdatePost::class)
->middleware('can:update,post'); // [tl! highlight]
```
Livewire will en... | |
244171 | class HttpKernel extends Kernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
... | |
244234 | <?php
namespace Livewire\Features\SupportLegacyModels;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
use LogicException;
class EloquentCollectionSynth extends Synth
{
public static $key = 'elcl';
public static function match($... | |
244246 | public function test_it_serialises_properties_from_model_that_has_not_been_persisted()
{
// @todo: Review this, as it's not quite correct, key "name" should be sent to the front end, even if not set, to match V2 functionality
$model = Author::make();
$rules = [
'model.name' => '... | |
244252 | class Foo extends Model
{
use Sushi;
protected $casts = ['baz' => 'array', 'bob' => 'array', 'lob' => 'array', 'zap' => 'array'];
protected function getRows()
{
return [[
'bar' => 'rab',
'bar_baz' => 'zab_rab',
'baz' => json_encode(['zab', 'azb']),
... | |
244256 | class ModelForAttributeCasting extends \Illuminate\Database\Eloquent\Model
{
use Sushi;
protected $guarded = [];
protected $casts = [
'normal_date' => 'date',
'formatted_date' => 'date:d-m-Y',
'date_with_time' => 'datetime',
'timestamped_date' => 'timestamp',
'integ... | |
244260 | <?php
namespace Livewire\Features\SupportErrorResponses;
use Livewire\Component as BaseComponent;
use Livewire\Livewire;
class BrowserTest extends \Tests\BrowserTestCase
{
public function test_it_shows_page_expired_dialog_when_session_has_expired()
{
Livewire::visit(Component::class)
->wa... | |
244262 | <?php
namespace Livewire\Features\SupportLocales;
use Illuminate\Support\Facades\App;
use Livewire\Livewire;
use Tests\TestComponent;
class UnitTest extends \Tests\TestCase
{
public function test_a_livewire_component_can_persist_its_locale()
{
// Set locale
App::setLocale('en');
$this... | |
244295 | <?php
namespace Livewire\Features\SupportFileUploads;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\WhitespacePathNormalizer;
class FileUploadConfiguration
{
public static function storage()
{
$disk = static::disk();
if (app()->runningUnitTests()) {
// We want to "... | |
244411 | <?php
namespace Livewire\Features\SupportNavigate;
use Laravel\Dusk\Browser;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\Dr... | |
244413 | public function test_navigate_scrolls_to_top_and_back_preserves_scroll()
{
$this->browse(function ($browser) {
$browser
->visit('/first-scroll')
->assertVisible('@first-target')
->assertNotInViewPort('@first-target')
->scrollTo('@fi... | |
244420 | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=123" data-navigate-track></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html> | |
244422 | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=123"></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html> | |
244423 | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=456" data-navigate-track></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html> | |
244424 | <html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="/test-navigate-asset.js?v=456"></script>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html> | |
244447 | <?php
namespace Livewire\Features\SupportDataBinding;
use Tests\BrowserTestCase;
use Livewire\Livewire;
use Livewire\Component;
use Livewire\Attributes\Computed;
class BrowserTest extends BrowserTestCase
{
function test_can_use_wire_dirty()
{
Livewire::visit(new class extends Component {
... | |
244542 | <?php
namespace Livewire\Tests;
use Livewire\Component;
use Livewire\Livewire;
class AlpineUiBrowserTest extends \Tests\BrowserTestCase
{
public function test_component_with_listbox_and_wire_model_live_should_not_cause_infinite_loop()
{
Livewire::visit(new class extends Component {
public... | |
244545 | <?php
namespace Livewire\Tests;
use Livewire\Component;
use Livewire\Livewire;
class UpdatingTableRowsTest extends \Tests\BrowserTestCase
{
public function test_component_renders_table_rows_and_updates_properly()
{
Livewire::visit([new class extends Component {
public function render() {
... | |
244568 | <?php
namespace Livewire\Exceptions;
use Symfony\Component\HttpKernel\Exception\HttpException;
class LivewirePageExpiredBecauseNewDeploymentHasSignificantEnoughChanges extends HttpException
{
public function __construct()
{
parent::__construct(
419,
'New deployment contains ch... | |
244593 | <p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"... | |
244594 | #!/usr/bin/env php
<?php
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
$status = (require_once __DIR__.'/bootstrap/app.php')
->handleCommand(ne... | |
244601 | <?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php... | |
244602 | <?php
return [
App\Providers\AppServiceProvider::class,
]; | |
244604 | <?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFa... | |
244607 | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to plac... | |
244612 | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized... | |
244613 | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving y... | |
244614 | <?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------... | |
244615 | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. T... | |
244631 | <?php
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/aut... | |
244643 | import argparse
import sys
import time
import warnings
sys.path.append('./') # to run '$ python *.py' files in subdirectories
import torch
import torch.nn as nn
from torch.utils.mobile_optimizer import optimize_for_mobile
import models
from models.experimental import attempt_load, End2End
from utils.activations imp... | |
244644 | try:
import onnx
print('\nStarting ONNX export with onnx %s...' % onnx.__version__)
f = opt.weights.replace('.pt', '.onnx') # filename
model.eval()
output_names = ['classes', 'boxes'] if y is None else ['output']
dynamic_axes = None
if opt.dynamic:
d... | |
244647 | olov7_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7_training.pt) [`yolov7x_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7x_training.pt) [`yolov7-w6_training.pt`](https://github.com/WongKinYiu/yolov7/releases/download/v0.1/yolov7-w6_training.pt) [`yolo... | |
244657 | def train(hyp, opt, device, tb_writer=None):
logger.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
save_dir, epochs, batch_size, total_batch_size, weights, rank, freeze = \
Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_... | |
244663 | """PyTorch Hub models
Usage:
import torch
model = torch.hub.load('repo', 'model')
"""
from pathlib import Path
import torch
from models.yolo import Model
from utils.general import check_requirements, set_logging
from utils.google_utils import attempt_download
from utils.torch_utils import select_device
dep... | |
244664 | import argparse
import time
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, check_requirements, check_imshow, non_max... | |
244665 | if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
parser.add_argument('--img-s... | |
244680 | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "0ab662ce",
"metadata": {},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\n",
"import torch\n",
"import cv2\n",
"from torchvision import transforms\n",
"import numpy as np\n",
"from utils.datasets ... | |
244725 | "\n",
" if shape[::-1] != new_unpad: # resize\n",
" im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n",
" top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n",
" left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n",
" im = cv2.copy... | |
244727 | "!git clone https://github.com/WongKinYiu/yolov7\n",
"%cd yolov7\n",
"!ls"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yfZALjuo-_Md",
"outputId": "88dbe003-898b-48ea-f374-42228d25a3cb"
},
"execution_count":... | |
244744 | "text": [
" im = (640, 640, 3)\n",
" im = <PIL.Image.Image image mode=RGB size=640x640 at 0x7F8E0F0CD9D0>\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"def xywh2xyxy(x):\n",
" # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y... | |
244750 | " [ 2.0000000e+00, 6.5209000e+01, 2.4051682e+02, 4.7865540e+02,\n",
" 4.9418790e+02, 0.0000000e+00, 5.7698834e-01],\n",
" [ 3.0000000e+00, 5.2892609e+00, 6.2162445e+01, 3.7209552e+02,\n",
" 5.8483594e+02, 0.0000000e+00, 8.7545133e-01],\n",
" [... | |
244758 | "\u001b[?25hRequirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in /usr/local/lib/python3.7/dist-packages (from packaging->onnxruntime) (3.0.9)\n",
"Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.7/dist-packages (from protobuf->onnxruntime) (1.15.0)\n",
"Requirement alread... | |
244759 | {
"cell_type": "code",
"source": [
"!# Download YOLOv7 code\n",
"!git clone https://github.com/WongKinYiu/yolov7\n",
"%cd yolov7\n",
"!ls"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yfZALjuo-_Md",
... | |
244766 | class BoundingBox:
def __init__(self, classID, confidence, x1, x2, y1, y2, image_width, image_height):
self.classID = classID
self.confidence = confidence
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.u1 = x1 / image_width
self.u2 = x2 / ima... | |
244767 | # YOLOv7 on Triton Inference Server
Instructions to deploy YOLOv7 as TensorRT engine to [Triton Inference Server](https://github.com/NVIDIA/triton-inference-server).
Triton Inference Server takes care of model deployment with many out-of-the-box benefits, like a GRPC and HTTP interface, automatic scheduling on multip... | |
244769 | from boundingbox import BoundingBox
import cv2
import numpy as np
def preprocess(img, input_shape, letter_box=True):
if letter_box:
img_h, img_w, _ = img.shape
new_h, new_w = input_shape[0], input_shape[1]
offset_h, offset_w = 0, 0
if (new_w / img_w) <= (new_h / img_h):
... | |
244777 | def cache_labels(self, path=Path('./labels.cache'), prefix=''):
# Cache dataset labels, check images and read shapes
x = {} # dict
nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate
pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(... | |
244778 | @staticmethod
def collate_fn4(batch):
img, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
s = torch.ten... | |
244782 | def random_perspective(img, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
border=(0, 0)):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = img.shap... | |
244803 | def plot_results_overlay(start=0, stop=0): # from utils.plots import *; plot_results_overlay()
# Plot training 'results*.txt', overlaying train and val losses
s = ['train', 'train', 'train', 'Precision', 'mAP@0.5', 'val', 'val', 'val', 'Recall', 'mAP@0.5:0.95'] # legends
t = ['Box', 'Objectness', 'Classif... | |
244811 | ut):
# Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
*args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
colors = {'black': '\033[30m', # basic colors
'red': '\033[31m',
'green... | |
244815 | ession(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
labels=()):
"""Runs Non-Maximum Suppression (NMS) on inference results
Returns:
list of detections, on (n,6) tensor per image [xyxy, conf, cls]
"""
nc = prediction.shap... | |
244816 | ession_kpt(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
labels=(), kpt_label=False, nc=None, nkpt=None):
"""Runs Non-Maximum Suppression (NMS) on inference results
Returns:
list of detections, on (n,6) tensor per image [xyxy, con... | |
244839 | class Detections:
# detections class for YOLOv5 inference results
def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
super(Detections, self).__init__()
d = pred[0].device # device
gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im... | |
244902 | # COCO 2017 dataset http://cocodataset.org
# download command/URL (optional)
download: bash ./scripts/get_coco.sh
# train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
train: ./coco/train2017.txt # 118287 images
val: ./coco/val2017.txt # 5000 images... | |
244903 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr... | |
244904 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr... | |
244905 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_l... | |
244906 | lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
momentum: 0.937 # SGD momentum/Adam beta1
weight_decay: 0.0005 # optimizer weight decay 5e-4
warmup_epochs: 3.0 # warmup epochs (fractions ok)
warmup_momentum: 0.8 # warmup initial momentum
warmup_bias_lr... | |
245260 | #!/usr/bin/env python
'''
face detection using haar cascades
USAGE:
facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
# local modules
from video import create_capture
f... | |
245267 | #!/usr/bin/env python
'''
VideoCapture sample showcasing some features of the Video4Linux2 backend
Sample shows how VideoCapture class can be used to control parameters
of a webcam such as focus or framerate.
Also the sample provides an example how to access raw images delivered
by the hardware to get a grayscale im... | |
245284 | #!/usr/bin/env python
'''
MSER detector demo
==================
Usage:
------
mser.py [<video source>]
Keys:
-----
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
import video
import sys
def main():
try:
video_src = sys.ar... | |
245304 | #!/usr/bin/env python
'''
Multithreaded video processing sample.
Usage:
video_threaded.py {<video device number>|<video file name>}
Shows how python threading capabilities can be used
to organize parallel captured frame processing pipeline
for smoother playback.
Keyboard shortcuts:
ESC - exit
spac... | |
245332 | if __name__ == '__main__':
import sys
import getopt
print(__doc__)
args, sources = getopt.getopt(sys.argv[1:], '', 'shotdir=')
args = dict(args)
shotdir = args.get('--shotdir', '.')
if len(sources) == 0:
sources = [ 0 ]
caps = list(map(create_capture, sources))
shot_idx = ... | |
245338 | #!/usr/bin/env python
'''
Video histogram sample to show live histogram of video
Keys:
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2 as cv
# built-in modules
import sys
# local modules
import video
class App():
def set_scale(self, val):... | |
245340 | import numpy as np
import cv2 as cv
import argparse
parser = argparse.ArgumentParser(description='This sample demonstrates the camshift algorithm. \
The example file can be downloaded from: \
https://www.bogotobogo.com/python/O... | |
245341 | import numpy as np
import cv2 as cv
import argparse
parser = argparse.ArgumentParser(description='This sample demonstrates the meanshift algorithm. \
The example file can be downloaded from: \
https://www.bogotobogo.com/python/... | |
245365 | from __future__ import print_function
import cv2 as cv
import argparse
max_value = 255
max_value_H = 360//2
low_H = 0
low_S = 0
low_V = 0
high_H = max_value_H
high_S = max_value
high_V = max_value
window_capture_name = 'Video Capture'
window_detection_name = 'Object Detection'
low_H_name = 'Low H'
low_S_name = 'Low S'... | |
245376 | from __future__ import print_function
import cv2 as cv
import argparse
def detectAndDisplay(frame):
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
frame_gray = cv.equalizeHist(frame_gray)
#-- Detect faces
faces = face_cascade.detectMultiScale(frame_gray)
for (x,y,w,h) in faces:
center ... | |
245392 | from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
import random as rng
rng.seed(12345)
def thresh_callback(val):
threshold = val
## [Canny]
# Detect edges using Canny
canny_output = cv.Canny(src_gray, threshold, threshold * 2)
## [Canny]
## [findContou... | |
245826 | package org.opencv.samples.opencv_mobilenet;
/*
// snippet was added for Android tutorial
//! [mobilenet_tutorial_package]
package com.example.myapplication;
//! [mobilenet_tutorial_package]
*/
//! [mobilenet_tutorial]
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
im... | |
245846 | import argparse
import cv2 as cv
import numpy as np
from common import *
def get_args_parser(func_args):
backends = (cv.dnn.DNN_BACKEND_DEFAULT, cv.dnn.DNN_BACKEND_HALIDE, cv.dnn.DNN_BACKEND_INFERENCE_ENGINE,
cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_BACKEND_VKCOM, cv.dnn.DNN_BACKEND_CUDA)
target... | |
245870 | import cv2 as cv
import argparse
import numpy as np
parser = argparse.ArgumentParser(description=
'Use this script to run Mask-RCNN object detection and semantic '
'segmentation network from TensorFlow Object Detection API.')
parser.add_argument('--input', help='Path to input image or video file. Skip ... | |
245876 | %YAML 1.0
---
################################################################################
# Object detection models.
################################################################################
# OpenCV's face detection network
opencv_fd:
load_info:
url: "https://github.com/opencv/opencv_3rdparty/raw/dn... | |
245880 | import cv2 as cv
import argparse
import numpy as np
import sys
import copy
import time
from threading import Thread
if sys.version_info[0] == 2:
import Queue as queue
else:
import queue
from common import *
from tf_text_graph_common import readTextMessage
from tf_text_graph_ssd import createSSDGraph
from tf_te... | |
245881 | def postprocess(frame, outs):
frameHeight = frame.shape[0]
frameWidth = frame.shape[1]
def drawPred(classId, conf, left, top, right, bottom):
# Draw a bounding box.
cv.rectangle(frame, (left, top), (right, bottom), (0, 255, 0))
label = '%.2f' % conf
# Print a label of clas... | |
246100 | <script id="codeSnippet5" type="text/code-snippet">
postProcess = function(result, labels, frame) {
let canvasOutput = document.getElementById('canvasOutput');
const outputWidth = canvasOutput.width;
const outputHeight = canvasOutput.height;
const resultData = result.data32F;
// Get the boxes(with ... | |
246116 | <script id="codeSnippet5" type="text/code-snippet">
postProcess = function(result, labels) {
let canvasOutput = document.getElementById('canvasOutput');
const outputWidth = canvasOutput.width;
const outputHeight = canvasOutput.height;
const resultData = result.data32F;
// Get the boxes(with class a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.