-
-
Save bikz05/d75d8f1d9a5f53e16875 to your computer and use it in GitHub Desktop.
import cv2 | |
import argparse | |
# Download the image used for this tutorial from here. | |
# http://goo.gl/jsYXl8 | |
# Read the image | |
ap = argparse.ArgumentParser(); | |
ap.add_argument("-i", "--image", required = True, help = "path to the image file"); | |
args = vars(ap.parse_args()); | |
# Read the image | |
image = cv2.imread(args["image"]); | |
# Convert the image into grayscale | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY); | |
# Get the size of the image | |
# Output is in the form of tuple | |
# (height of image , width of image, no of channels) | |
print image.shape; # OUPTUT = (476, 640, 3) | |
# Accessing single pixel value | |
# image[y co-ordinate, x co-ordinate] | |
# Output is in the form of [B,G,R] | |
print image[379, 383]; # OUPTUT = [207 151 143] | |
# To get value of only one channel, use | |
# image[y co-ordinate, x co-ordinate, channel index] | |
# Channel are indexed as - | |
# 0 for Blue, 1 for Green and 2 for Red | |
# In the example below we print the Blue Channel Value | |
print image[379, 383, 1]; # OUPTUT = 151 | |
# Clone the image | |
image_copy = image.copy(); | |
# Display the image | |
cv2.imshow("Image", image); | |
cv2.waitKey(); # The program will wait till eternity, |
Hey! Same problem here! Can you please show us the way to solve this error: the following arguments are required: -i/--image. Thanks
Example of usage:
python3.5 opencv_basic.py -i fileName.png
Thank you isabelatelles!
hello isabelatelles
i am not able to understand wat u r trying to do
pls explain
In command line type:
python opencv_basic.py --image pathNameToThe image
make sure pathNameToThe image is like C:\Users\Saurav\Desktop\image.jpg
and put opencv_basic.py in the pwd
Hi, thanks for your code! I still have issues on how to used this code. (I am very new to python by the way and am using Python 3.7). Thank for your time.
Olá
como executar este código. mostra erro de análise no diretório do caminho, assim como -i / - imagem
Olá, execute o seguinte trecho no seu prompt: python opencv_basic.py --i nomedoseuarquivodeimagem.png setado para o local do arquivo de origem do projeto no seu disco local.
Oi, obrigado pelo seu código! Ainda tenho problemas em como usar esse código. (Eu sou muito novo para python e estou usando o Python 3.7). Obrigado pelo seu tempo.
Olá, execute o seguinte trecho no seu prompt: python opencv_basic.py --i nomedoseuarquivodeimagem.png setado para o local do arquivo de origem do projeto no seu disco local.
-- coding: utf-8 --
"""
Created on Wed Jun 10 16:30:20 2020
@author: siddh
"""
import cv2
import argparse
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True,
help = 'path to input image')
ap.add_argument('-c', '--config', required=True,
help = 'path to yolo config file')
ap.add_argument('-w', '--weights', required=True,
help = 'path to yolo pre-trained weights')
ap.add_argument('-cl', '--classes', required=True,
help = 'path to text file containing class names')
args = ap.parse_args()
def get_output(model):
layer_names = model.getLayerNames()
output_layers = [layer_names[i[0]-1]for i in model.getUnconnectedOutLayers()]
return output_layers
def draw_preds(img, class_id, confidence, x, y, x_plus_w, y_plus_h):
label = str(classes[class_id])
color = COLORS[class_id]
cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)
cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
image=img[y:y_plus_h,x:x_plus_w]
cv2.imshow('crop',image)
cv2.imwrite("cropped.jpg",image)
image = cv2.imread(args.image)
Width = image.shape[0]
Height = image.shape[1]
scale_factor = 0.00392
classes = None
with open(args.classes, 'r') as f:
classes = [line.strip() for line in f.readlines()]
COLORS = np.random.uniform(0, 255, size=(len(classes), 3))
model = cv2.dnn.readNet(args.weights, args.config)
blob = cv2.dnn.blobFromImage(image, scale_factor, (416,416), (0,0,0), True, crop=False)
model.setInput(blob)
outputs = model.forward(get_output(model))
class_ids = []
confidences = []
bounding_boxes = []
conf_threshold = 0.5
nms_threshold = 0.4
for output in outputs:
for detection in output:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0]*Width)
center_y = int(detection[1]*Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
bounding_boxes.append([x,y,w,h])
indices = cv2.dnn.NMSBoxes(bounding_boxes,confidences,conf_threshold,nms_threshold)
for i in indices:
i = i[0]
box = bounding_boxes[i]
x,y,w,h = box[0],box[1],box[2],box[3]
draw_preds(image,class_ids[i],confidences[i],round(x),round(y),round(x+w),round(y+h))
cv2.imshow("license plate detection",image)
cv2.waitKey()
cv2.imwrite("plate-detection.jpg",image)
cv2.destroyAllWindows()
Below Error: //kindly help anyone. what is the wrong with this code
D:\pythonall\ANPR-master>python test.py -i /path/to/image -c /path/to/config_file -w /path/to/weights/ -cl /path/to/obj.names
[ WARN:0@0.020] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('/path/to/image'): can't open/read file: check file path/integrity
Traceback (most recent call last):
File "D:\pythonall\ANPR-master\test.py", line 43, in
Width = image.shape[0]
AttributeError: 'NoneType' object has no attribute 'shape'
how to run this code. it shows parsing error on the path directory just like -i/--image