def fd_SIFT_v2(image): gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) sift = cv2.xfeatures2d.SIFT_create() kp = sift.detect(gray, None) image = cv2.drawKeypoints(gray, kp, image) cv2.show('sift_keypoints.jpg', image) return kp
def sift_detection(): img = cv.imread('./../wu.jpg') gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY) sift = cv.xfeatures2d.SIFT_create() kp = sift.detect(gray, None) img = cv.drawKeypoints(gray, kp, img) cv.show('sift_keypoints', img)
def binary_HSV(img): hsv_low = np.array([25, 75, 165]) hsv_high = np.array([40, 255, 255]) hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) # BGR转HSV dst = cv2.inRange(hsv, hsv_low, hsv_high) # 通过HSV的高低阈值,提取图像部分区域 cv2.show("Binary HSV Outpt:", dst) return dst
def birdsEyeTrans(self): IMAGE_H = 480 IMAGE_W = 640 src = np.float32([[0, IMAGE_H], [1207, IMAGE_H], [0, 0], [IMAGE_W, 0]]) dst = np.float32([[569, IMAGE_H], [711, IMAGE_H], [0, 0], [IMAGE_W, 0]]) M = cv2.getPerspectiveTransform(src, dst) # The transformation matrix Minv = cv2.getPerspectiveTransform(dst, src) # Inverse transformation img = self.process_image(self, self.capture) # Read the test img img = img[450:(450 + IMAGE_H), 0:IMAGE_W] # Apply np slicing for ROI crop warped_img = cv2.warpPerspective(img, M, (IMAGE_W, IMAGE_H)) # Image warping cv2.imshow(cv2.cvtColor(warped_img, cv2.COLOR_BGR2RGB)) # Show results cv2.show()
import cv2 cap = cv2.VideoCapture(0) cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) while True: retrieval, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) #face_detect() cv2.show('', frame) cv2.release() cv2.destroyAllWindows()
os.mkdir(path + str(ID)) print("Directory " + path + str(ID) + " Created") except FileExistsError: print("Directory " + path + str(ID) + " already exists.") sampleN = 0 while (1): ret, img = cap.read() frame = img.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: sampleN += 1 cv2.imwrite(path + str(ID) + "\\" + str(sampleN) + ".jpg", gray[y:y + h, x:x + w]) cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) cv2.waitKey(100) cv2.show('img', img) cv2.waitKey(1) if (sampleN > 40): break
def Display_image(img): cv2.show(img) cv2.waitKey(-1) #Display_image(example1_gray)
while (True): print('시작') start = input('엔터키 입력') try: if start == '': for i in range(0, 5): print(os.listdir(pathList)[i]) original_image = cv2.imread(pathList + "/" + os.listdir(pathList)[i]) if original_image is None: error = np.zeros((1000, 1000), np.uint8) cv2.putText(error, "No file", (50, 300), cv.FONT_HERSHEY_SIMPLEX, 4, (255, 255, 255), 2) cv2.namedWindow("window 2") cv2.show('window 2', error) key = cv2.waitKey(0) if key == 27: break elif key == 13: continue original_image = cv2.resize( original_image, dsize=(int(original_image.shape[1] / 6), int(original_image.shape[0] / 8)), interpolation=cv2.INTER_AREA) height, width = original_image.shape[:2] #print("height: %d width: %d" %(height,width)) cv2.namedWindow("window 1", cv2.WINDOW_NORMAL) cv2.imshow("window 1", original_image)
KP = 15 KD = 5 def initialize_motors(): gpio.setmode(gpio.board) gpio.setup(L_MOTOR_PIN, gpio.out) gpio.setup(R_MOTOR_PIN, gpio.out) l_motor = gpio.PWM(L_MOTOR_PIN, 50) r_motor = gpio.PWM(R_MOTOR_PIN, 50) l_motor.start(100) r_motor.start(100) def drive_motor(motor, percent_speed): duty_cycle = percent_speed * 100 motor.ChangeDutyCycle(duty_cycle) ########################################## camera = PiCamera() raw_capture = PiRGBArray(camera) time_sleep(1) for frame in camera.capture_continous(raw_capture, format="bgr", use_video_port=true): img = frame.array cv2.show('Raw image', img) raw_capture.truncate(0) camera.close()
fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output2.avi', fourcc, 20, (1000, 1000)) while (True): ret, frame = cap.read() frame = cv2.flip(frame, flipCode=1) ## flipped sideways #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) cv2.imshow('frame', frame) out.write(frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() out.release() cap = cv2.VideoCapture('output2.avi') while (cap.isOpened()): ret, frame = cap.read() cv2.show('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
def camera(): authenticator = IAMAuthenticator( apikey="ZQBgX2TPs2CmC3wNLWGEr7X3xDmq42sDsqTZVCsjdke8") flag = False obj = VisualRecognitionV4(version='2021-03-25', authenticator=authenticator) obj.set_service_url( service_url= 'https://api.us-south.visual-recognition.watson.cloud.ibm.com/instances/2fa93f7c-36f0-48f9-abb1-15845fbe94e1' ) while True: success, img = cap.read() cv2.imwrite('4.jpg', img) with open('4.jpg', 'rb') as honda_file, open('4.jpg', 'rb') as dice_file: result = obj.analyze( collection_ids=[ "17951ae7-0169-4551-ac19-a3864c7eed65", '17951ae7-0169-4551-ac19-a3864c7eed65' ], features=[AnalyzeEnums.Features.OBJECTS.value], images_file=[ FileWithMetadata(honda_file), ], threshold=0.15).get_result() #print(json.dumps(result, indent=2)) img = cv2.imread('4.jpg') try: left = result['images'][0]['objects']['collections'][0]['objects'][ 0]['location']['left'] top = result['images'][0]['objects']['collections'][0]['objects'][ 0]['location']['top'] width = result['images'][0]['objects']['collections'][0][ 'objects'][0]['location']['width'] height = result['images'][0]['objects']['collections'][0][ 'objects'][0]['location']['height'] img = cv2.imread('4.jpg') cv2.rectangle(img, (left, top), (left + width, top + height), (255, 0, 0), 2) name = result['images'][0]['objects']['collections'][0]['objects'][ 0]['object'] with open('data.txt', 'r') as f: f.write(str(name)) cv2.putText(img, name, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2) cv2.imshow('gasm', img) k = cv2.waitKey(30) & 0xff if k == 27: # press 'ESC' to quit break cv2.show('gasm', img) if name == 'gun' and flag == False: flag = True SendMail() except: cv2.imshow('gasm', img) # pass # cv2.show('gasm',img) cap.release() # cv2.waitKey(0) cv2.destroyAllWindows()
from PIL import Image import numpy as np from tools.deeplab import Deeplab capture = cv2.VideoCapture("input_video/demo.mp4") fps = capture.get(cv2.CAP_PROP_FPS) size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) print("fps: {}\nsize: {}".format(fps, size)) # 读取视频时长(帧总数) total = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) print("[INFO] {} total frames in video".format(total)) # 调用VideoWrite()函数 videoWrite = cv2.VideoWriter( filename='output/Video.avi', fourcc=cv2.VideoWriter_fourcc(*"MPEG"), fps=fps, frameSize=size, isColor=True, ) index = 0 deeplab = Deeplab() while capture.isOpened(): # 读取某一帧 ref, frame = capture.read() frame = frame[:, :, ::-1] # 进行检测 frame = deeplab.main(frame, index, total) frame = frame[:, :, ::-1].astype(dtype=np.uint8) videoWrite.write(frame) cv2.show(frame) index += 1
import scipy as sp import numpy as np import scipy.ndimage as nd import matplotlib.pyplot as plt import cv2 img = cv2.imread('C:\Users\Debika Dutt\Documents\UB\CSE573\Bridge.jpg', 0) LoG = nd.gaussian_laplace(img, 2) thres = np.absolute(LoG).mean() * 0.75 output = sp.zeros(LoG.shape) w = output.shape[1] h = output.shape[0] for y in range(1, h - 1): for x in range(1, w - 1): patch = LoG[y - 1:y + 2, x - 1:x + 2] p = LoG[y, x] maxP = patch.max() minP = patch.min() if (p > 0): zeroCross = True if minP < 0 else False else: zeroCross = True if maxP > 0 else False if ((maxP - minP) > thres) and zeroCross: output[y, x] = 1 cv2.imshow("img", output) cv2.show()
import cv2 import numpy as np imagen = cv2.imread("/home/Pictures/sign_DoubleCurve.png") imagen = cv2.cvtColor(imagen, cv2.COLOR_BGR2HSV) imagen = np.array(image1, dtype=np.float64) random_bright = .5 + np.random.uniform() image[:, :, 2] = image[:, :, 2] * random_bright image[:, :, 2][image[:, :, 2] > 255] = 255 image = np.array(image, dtype=np.uint8) image = np.cv2.cvtColor(image) cv2.show(image, "imagen.png")
1、没有安装tesseract.exe (pip install py..过了) - 安装了之后,去找.py文件,在默认路径前添加一个r,不然 / 的符号, windows系统无法识别 - r:保持字符原始值的意思 2、该模板的中文版本可能不好用,可以直接使用百度OCR去进行文字识别 3、目前还没有需要识别文字,可以去尝试识别英文即可 """ from PIL import Image import pytesseract import cv2 import os preprocess = "blur" image = cv2.imread("./images/4.png") gray = cv2.cvtColor(image, cv2.COLOR_BGR2BGRA) if preprocess == "thresh": gray = cv2.medianBlur(gray, 3) filename = "{}.png".format(os.getpid()) cv2.imwrite(filename, gray) text = pytesseract.image_to_string(Image.open(filename)) print(text) os.remove(filename) cv2.show("Image", image) cv2.imshow("Output", gray) cv2.waitKey(0)
def main(): img = readImage(sys.argv[1]) canny = findCannyEdges(img) contours = findContours(canny) cv2.imshow('img',contours) cv2.show()
for face_encoding in face_encodings: matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" if True in matches: first_match_index = match.index(True) name = known_face_names[first_match_index] process_this_frame = not process_this_frame for (top, right, bottom, left), name in zip(face_locations, face_names): top *= 4 right *= 4 bottom *= 4 left *= 4 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) cv2.show('Video', frame) if cv2.waitkey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
""" Created on Sat Feb 16 8:19:21AM 2019 @author: Matt-Gleich How to convert BRG to other color-spaces such as HSV or Gray-scale """ import numpy as np import cv2 photo_path = '/Users/matthewgleich/Desktop/First/CV2_Test_Images/Solid_Red_Sized__25214.1507754519.jpg' img = cv2.imread(photo_path, 0) rows, cols = img.shape M = cv2.getRotationMatrix2d((cols / 2, rows / 2), 90, 1) dst = cv2.warpAffine(img, M(cols, rows)) cv2.show(img)