def processImg(self, img): #Array Processing if self.color == "RGB": img = cv.cvtcolor(img, cv.BGR2RGB) elif self.color == "GRAY": img = cv.cvtcolor(img, cv.BGR2GRAY) img = imutils.resize(width=self.width, height=self.height) #Conversions img = Image.fromarray(img) img = ImageTK.PhotoImage(image) return img
def reshapedata(imdata, imlabel): print(len(imdata)) for i in range(0, len(imdata)): # for i in range(1,5): # this data is the in the format of 3072 array elements temp = imdata[i] #print(temp) #print(len(temp)) # to reshape the data img = np.reshape(temp, (3, 32, 32)).t #print(img.shape) # convert the numpy array into the rgb format img = image.fromarray(img, 'rgb') # to see the image without correct orientation #plt.imshow(img) #plt.show() # img is in rotated format, so we need to rotate the image # to get the original orientation img = img.rotate(270) # here gray conversion is done: in our application color images are not need because we # can get the same information in the gray image. # benefit of using gray image : it will reduce the calculations by 3(rgb have 3 channels) img = cv2.cvtcolor(np.array(img), cv2.color_rgb2bgr) img = cv2.cvtcolor(np.array(img), cv2.color_bgr2rgb) # just to make sure that every image is 32*32 # img = cv2.resize(img, (32,32)) # to see the image in the correct orientation # plt.imshow(img) # plt.show() # just to verify that every label is int if type(imlabel[i]) != type(2): continue class_num = imlabel[i] # print(labels[class_num]) # break # to create training data: # i have appened the image data and the label # temp[0]: this is image # temp[1]: this is label temp = [img, class_num] trainingdata.append(temp)
def dotransrawimage(self): self.transrawimage = image.new( "l", (self.rawimage.width, self.rawimage.height)) for r in self.lirect: im = self.rawimage.crop(r) cv_im = cv.cvtcolor(np.asarray(im), cv.color_rgb2bgr) hsv = cv.cvtcolor(cv_im, cv.color_bgr2hsv) _, _, v = cv.split(hsv) avg = np.average(v.flatten()) pixels = im.load() for j in range(im.height): for i in range(im.width): hv = v[j, i] if hv < avg * 1.2: #im.putpixel ((i, j), 0) #slow pixels[i, j] = 0 else: im.putpixel((i, j), (255, 255, 255, 255)) self.transrawimage.paste(im, (int(r[0]), int(r[1])), mask=None) self.drawtransimagedisp()
def gen(): """ video streaming Geneatorr function.""" cap = cv2.VideoCapture('test.mp4') while (cap.isOpened()): #capture frame-by-frame ret, frame = cap.read() if not ret: frame = cv2.VideoCapture("test.mp4") continue if ret: image = cv2.resize(frame, (0, 0), None, 1, 1) gray = cv2.cvtcolor(image, cv2.COLOR_BGR2GRAY) fgmask = sub.apply(gray) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) closing = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel) opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel) dilation = cv2.dilate(opening, kernel) retvalbin, bins = cv2.threshold(dilation, 220, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) minarea = 400 maxarea = 50000 for i in range(len(contours)): if hierarchy[0, i, 3] == -1: area = cv2.contourArea(contours[i]) if minarea < area < maxarea: cnt = contours[i] M = cv2.moments(cnt) cx = int(M['m10'] / M['m00']) cy = int(M['m01'] / M['m00']) x, y, w, h = cv2.boundingRect(cnt) cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.puttext(image, str(cx) + "," + str(cy), (cx + 10, cy + 10), cv2.FONT_HERSHEY_SIMPLEX, .3, (0, 0, 255), 1) cv2.drawMarker(image, (cx, cy), (0, 255, 255), cv2.MARKER_CROSS, markerSize=8, thickness=3, line_type=cv2.LINE_8) frame = cv2.imencode('.jpg', image)[1].tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') time.sleep(0.1) key = cv2.waitKey(20) if key == 27: break
def align_and_combine(data_path, output_path, size): # resizing the image with the source image size folder_out = output_path if not os.path.exists(folder_out): os.makedirs(folder_out) # Scan all files on target folder cnt = 1 print("align and resizing for training...") files = [f for f in listdir(data_path) if isfile(join(data_path, f))] total = len(files) for f in files: fn, ext = os.path.splitext(f) if ext.lower() == '.jpg': # print("%d / %d, File Name: %s\n" % (cnt, total, f)) sys.stdout.write("\r%d / %d, File Name: %s\n" % (cnt, total, f)) sys.stdout.flush() cnt += 1 jpg_path = os.path.join(data_path, f) jpg_img = cv2.imread(jpg_path) if type(jpg_img) == None.__class__: # check if the image file is damaged or not os.remove(jpg_path) continue if len(jpg_img.shape) != 3: # Gray color image print(" --- gray color --- ") jpg_img = cv2.cvtcolor(jpg_img, cv2.COLOR_GRAY2RGB) h, w = jpg_img.shape[:2] # Resize the image with (size , size) new_jpg_img = cv2.resize(jpg_img, (size, int(size * h / w))) # create a combined image with size (size, 2*size) combined = np.zeros((size, size * 2, 3), dtype=np.uint8) # aligned_jpg_canvas[ combined[int(size / 2 - size * h / w / 2):int(size / 2 - size * h / w / 2) + int(size * h / w), :size] \ = new_jpg_img combined[int(size / 2 - size * h / w / 2):int(size / 2 - size * h / w / 2) + int(size * h / w), size:] \ = new_jpg_img # save combined image in different folders new_combined_path = os.path.join(folder_out, fn + '.png') cv2.imwrite(new_combined_path, combined)
def binarizeHSV(inCvBGR): outCvGray = cv2.inrange( cv2.cvtcolor(inCvBGR, cv2.COLOR_BGR2HSV), (int(p.visionParams[p.hueMin]), int( p.visionParams[p.satMin]), int(p.visionParams[p.valMin])), (int(p.visionParams[p.hueMax]), int( p.visionParams[p.satMax]), int(p.visionParams[p.valMax]))) outCvGray = cv2.erode(outCvGray, None, iterations=int(p.visionParams[p.binErIter])) return cv2.dilate(outCvGray, None, iterations=int(p.visionParams[p.binDiIter]))
def _align_and_combine(data_path, output_path, size): # resizing the image with the source image size folder_out = output_path if not os.path.exists(folder_out): os.makedirs(folder_out) # Scan all files on target folder cnt = 0 logger.log_print(" Scan for align and resizing ...\n") files = [ f for f in os.listdir(data_path) if os.path.isfile(os.path.join(data_path, f)) ] total = len(files) for f in files: fn, ext = os.path.splitext(f) if ext.lower() == '.jpg': cnt += 1 # logger.log_print(" {} / {}, File Name: {}\n" .format(cnt, total, f)) sys.stdout.write(" {} / {}, File Name: {}\n".format( cnt, total, f)) jpg_path = os.path.join(data_path, f) jpg_img = cv2.imread(jpg_path) if len(jpg_img.shape) != 3: # Gray color image logger.log_print(" --- gray color --- \n") jpg_img = cv2.cvtcolor(jpg_img, cv2.COLOR_GRAY2RGB) h, w = jpg_img.shape[:2] # Resize the image with (size , size) new_jpg_img = cv2.resize(jpg_img, (size, int(size * h / w))) # create a combined image with size (size, 2*size) combined = np.zeros((size, size * 2, 3), dtype=np.uint8) # aligned_jpg_canvas[ combined[int(size / 2 - size * h / w / 2):int(size / 2 - size * h / w / 2) + int(size * h / w), :size] \ = new_jpg_img # save combined image in different folders new_combined_path = os.path.join(folder_out, fn + '.png') cv2.imwrite(new_combined_path, combined) return cnt
def sketch(image): #converting image to gray scale img_gray = cv2.cvtcolor(image, cv2.COLOR_BGR2GRAY) #blurring image to remove noise img_blur = cv2.GassianBlur(img_gray, (3, 3), 0) #extracting edges edges = cv2.Canny(img_blur, 10, 80) #applying threshold inverse ret, mask = cv2.threshold(edges, 50, 255, cv2.THRESH_BINARY_INV) return mask
def screenRecorder(): fourcc = cv2.VideoWritter_fourcc(*'XVID') out = cv2.VideoWritter("output.avi", fourcc, (1366, 768)) while True: img = ImageGrab.grab() img_np = np.array(img) frame = cv2.cvtcolor(img_np, cv2.COLOR_BGRGB) cv2.imshow("Screen Recorder", frame) cv2.write(frame) if cv2.waitKey(1) == 27: break out.release() cv2.destroyAllWindow()
import numpy as numpy labels = [ "airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck" ] im_size = 32 * 32 * 3 # モデルデータを読み込み model.load_weights('cifar10-mlp-weight.h5') # OpenCVを使って画像を読み込む im = cv2.imread('test-car.jpg') # 色空間を変換してリサイズ im = cv2.cvtcolor(im, cv2.COLOR_BGR2RGB) im = cv2.resize(im, (32, 32)) plt.imshow(im) #画像を出力 plt.show() # MLPで学習した画像データに合わせる im = im.reshape(im_size).astype('float32') / 255 # 予測する r = model.predict(np, array([im]), batch_size=32, verbose=1) res = r[0] # 結果を表示する for i, acc in enumerate(res): print(labels[i], "=", int(acc * 100)) print("---")
def image_reader(self): ''' read the image using the given path ''' self.image = cv2.imread(self.image_path) self.grayscale = cv2.cvtcolor(self.image, cv2.COLOR_BGR2GRAY)
background = 0 ##capture the background in range of 60 for i in range(30): ret,background = cap.read() background = np.flip(background, axis=1) #flipping the frame we are reading #READING FROM VIDEO while (cap.isOpened()): ret, img = cap.read() if not ret: break #CONVERTING THE IMAGE- BGR TO HSV hsv = cv2.cvtcolor(img, cv2.COLOR_BGR2HSV) ##setting lower_red and upper_red values for mask1 and mask22 lower_red = np.array([100,40,40]) upper_red = np.array([100,255,255]) mask1 = cv2.inRange(hsv, lower_red, upper_red) lower_red = np.array([155,40,40]) upper_red = np.array([180,255,255]) mask2 = cv2.inRange(hsv, lower_red, upper_red) mask1 = mask1 + mask2 #SEGMENTING THE MASK PART FROM FRAMES mask1 = cv2.morphologyEx(mask1, cv2.MORPH_OPEN, np.ones((3,3), np.uint8), iterations=2) mask1 = cv2.morphologyEx(mask1, cv2.MORPH_DILATE, np.ones((3,3), np.uint8), iterations=1)
noise_detect = cv2.CascadeClassifier("haarcascade_mcs_nose.xml") face_detect = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml") if face_detect.empty(): raise IOError('Unable to haarcascade_frontalface_alt.xml file') if eyes_detect.empty(): raise IOError('Unable to haarcascade_eye.xml file') if noise_detect.empty(): raise IOError('Unable to haarcascade_mcs_nose.xml file') capture = cv2.VideoCapture(0) while True: ret, capturing = capture.read() x, y, w, h = 0, 0, 0, 0 resize_frame = cv2.resize(capturing, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) gray = cv2.cvtcolor(resize_frame, cv2.COLOR_BGR2GRAY) if face_detect.empty(): raise IOERROR('Unable ') resize_frame = cv2.resize(capturing, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) gray = cv2.cvtcolor(resize_frame, cv2.COLOR_BGR2GRAY) face_detection = face_detect.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in face_detection: cv2.rectangle(resize_frame, (x, y), (x + w, y + h), (0, 0, 255), 10)
def sketch(image): img_gray = cv2.cvtcolor(image,cv2.BGR2GRAY) img_gray_blur = cv2.GussianBlur(img_gray,(5,5),0) canny_edge = cv2.Canny(img_gray_blur,10,70) ret,mask = cv2.threshold(canny_edge, 70 , 255, cv2.THRESH_BINARY_INV)
import cv2 #Read pictures and zoom for easy display img=cv2.imread("random_image.jpg") height, width=img.shape[:2] size=(int(width * 0.2), int(height * 0.2)) #Zoom img=cv2.resize(img, size, interpolation=cv2.inter_area) #bgr to hsv hsv=cv2.cvtcolor(img, cv2.color_bgr2hsv) #Mouse click response event def getposhsv(event, x, y, flags, param): if event==cv2.event_lbuttondown: print("hsv is", hsv[y, x]) def getposbgr(event, x, y, flags, param): if event==cv2.event_lbuttondown: print("bgr is", img[y, x]) cv2.imshow("imagehsv", hsv) cv2.imshow("image", img) cv2.setmousecallback("imagehsv", getposhsv) cv2.setmousecallback("image", getposbgr) cv2.waitkey(0)
import numpy as np import pandas as pd first_frame=None """ status_list=[None,None] times=[] df=pandas.DataFrame(columns=["Start","End"]) """ video=cv2.VideoCapture(0) while True: check,frame=video.read() #status=0 gray=cv2.cvtcolor(frame,cv2.COLOR_BGR2GRAY) gray=cv2.GaussianBlur(gray,(21,21),0) if first_frame is None: first_frame=gray continue delta_frame=cv2.absdiff(first_frame,gray) thresh_delta=cv2.threshold(delta_frame,30,255,cv2.THRESH_BINARY)[1] thresh_delta=cv2.dilate(thresh_delta,None,iterations=0) (_,cnts,_)=cv2.findContours(thresh_delta.copy(),cv2.RETR_EXTRNAL,cv2.CHAIN_APPROX_SIMPLE) for contour in cnts: if cv2.contourArea(contour)<1000: continue #status=1
import numpy as np import matplolib.pyplot as plt import cv2 as cv im = cv.imread('poster.png') img = cv.cvtcolor(im, cv.COLOR_BGR2RGB) kernal = np.ones((5, 5), np.float32) / 25 dest = cv.filter2D(img, -1, kernal) blur = cv.blur(img, (5, 5)) gablur = cv.GaussianBlur(img, (5, 5), 0) median = cv.medianBlur(img, 5) bilateral_filter = cv.bilateralFilter(img, 9, 75, 75) images = [dest, blur, gablur, median, bilateral_filter] titles = [ '2D convulation', 'blur', 'Gaussian Blur', 'median', 'bilateral filter' ] for i in range(4): plt.subplot(2, 2, i + 1) plt.imshow('blurring', images[i]) plt.title(titles[i]) plt.show()
import numpy as np import cv2 color = cv2.imread("butterflay.jpg", 1) cv2.imshow("Image", color) cv2.moveWindow("Image", 0, 0) print(color.shape) height, width, channels = color.shape b, g, r = cv2.split(color) rgb_split = np.empty([height, width * 3, 3], 'uint8') rgb_split[:, 0:width] = cv2.merge([b, b, b]) rgb_split[:, width:width * 2] = cv2.merge([g, g, g]) rgb_split[:, width * 2:width * 3] = cv2.merge([r, r, r]) cv2.imshow("channels", rgb_split) cv2.moveWindows("channels", 0, height) hsv = cv2.cvtcolor(color, cv2.COLOR_BGR2HV) h, s, v = cv2.split(hsv) hsv_split = np.concatenate((h, s, v), axis=1) cv2.imshow("Split.HSV", hsv_split) cv2.waitKey(0) cv2.destroyAllWindows()
def extract_color_histogram(image,bins=(8,8,8)): #extract a 3D color histogramfrom the HSV color space using the supplies numbr of 'bins' per channel. hsv = cv2.cvtcolor(image,cv2.COLOR_BGR2HSV) hist = cv2.calcHist([hsv], [0,1,2], None, bins, [0,180,0,256,0,256])
eye_cascade = cv2.CascadeClassifier('haar_cascade_files/haarcascade_eye.xml') if case_cascade.empty(): print(" unable to load the face cascade classifier xml file ") if eye_cascade.empty(): print("unable to load the eye cascade classifier xml file ") cap = cv2.videocapture(0) ds_factor = 0.5 while true: frame = cap.read() frame = cv2.resize(frame, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_AREA) gray = cv2.cvtcolor(frame, cv2.colour_BGR2GRAY) faces = face_cascade.detectMultiscale(gray, 1.3, 5) for (x, y, w, h) in faces: roi_gray = gray[y:y + h, X:X + w] roi_colour = frame[y:y + h, x:x + w] eyes = eye_cascade.detectmultiscale(roi_gray) for (x_eye, y_eye, w_eye, h_eye) in eyes: centre = (int(x_eye=0.5 * w_eye)) color = (0, 255, 0) thickness = 3 cv2.circle(roi_color, centre, radius, colour, thickness) cv2.imshow('eye detector', frame) c = cv2.waitkey(1) #if c == 27: # break
import numpy as mp import cv2 from matplotlib import pyplot as plt from PIL import image, ImageFilter image2 = cv2.imread('images.png') image2 = cv2.cvtcolor(image, cv2.COLOR_BGR2GRAY) figure_size = 9 new_image = cv2.blur(image2, (figure_size, figure_size)) plt.figure(figuresize=(11, 6)) plt.subplot(121), plt.imshow(image2, cmap='gray'), plt.title(original) plt.xticks([]), plt.yticks([]) plt.subplot(122), plt.imshow(new_image, cmap='gray'), plt.title(mean_filter) plt.xticks([]), yticks([]) plt.show() # MEDIAN FILTER import cv2 import numpy as np from matplotlib import pyplot as plt image = cv2.imread('new.jpg', cv2.COLOR_BGR2GRAY) cv2.imshow("input", image) image = cv2.medianBlur(image, 5) cv2.imshow("output", image)
import cv2 import numpy as np faceDetect=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cam=cv2.videocapture(0) id=raw_input('emter user id') sampleNum=0 while(True): ret,img=cam.read() gray=cv2.cvtcolor(img,cv2.COLOR_BGR2GRAY) faces=faceDetect.detectMultiScale(gray,1.3,5) for(x,y,w,h) in faces: sampleNum=sampleNum+1 cv2.imwrite("dataset/user."+str(id)+"."+str(sampleNum)+".jpg") cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2) cv2.waitKey(100) cv2.imshow("face",img) cv2.waitKey(10) if(sampleNum>60): break cam.release() cv2.destroyAllWindows()
#to capture frames from the camera ret, frame = capture.read() #get hand date from the rectangle window cv2.rectangle(frame, (100,100), (300,300), (0,255,0), 0) crop_image = frame[100:300, 100:300 #apply gaussian blur blur = cv2.GaussianBlur(crop_image, (3, 3), 0) #change color from BGR to HSV hsv = cv2.cvtcolor(blur, cv2.COLOR_BGR2HSV) #create a binary image with where white will be skin color and rest is black mask2 = sv2.inRange(hsv, np.array([2,0,0]), np.array([2,0,0])) #kernal for morphological transformation kernal = np.ones([5,5]) #apply morphological tranformation to filter out the background noise dilation = cv2.dilate(mask2, kernal, iterations=1) erosion = cv2.erode(dilation, kernal, iterations=1) #gussion blur and threshold
or master_channel != target_channel): return -1 else: total_diff = 0.0 dst = cv2.absdiff(master, target) dst = cv2.pow(dst, 2) mean = cv2.mean(dst) total_diff = mean[0]**(1 / 2.0) return total_diff if __name__ == '__main__': # validate the input arguments if (len(sys.argv) != 4): help_message() sys.exit() img = cv2.imread(sys.argv[1], cv2.imread_color) img_marking = cv2.imread(sys.argv[2], cv2.imread_color) mask = cv2.cvtcolor( img_marking, cv2.color_bgr2gray ) # dummy assignment for mask, change it to your result # read video file output_name = sys.argv[3] + "mask.png" cv2.imwrite(output_name, mask)
import cv2 #starting camera cap=cv2.VideoCapture(2) tp1=cap.read()[1] #take 1 tp2=cap.read()[1] #take2 tp3=cap.read()[1] #take3 #to make more perfect gray1=cv2.cvtcolor(tp1,cv2.COLOR_BGR2GRAY) #converting into gray gray2=cv2.cvtcolor(tp2,cv2.COLOR_BGR2GRAY) gray3=cv2.cvtcolor(tp3,cv2.COLOR_BGR2GRAY) #now creatinig image diffrentiater def img_diff(x,y,z): #diff bw x,y---gray1,gray2--d1 d1=csv2.absdiff(x,y) #diff bw y,z---gray2,gray3---d2 d2=cv2.absdiff(y,z) #abs diff d1,d2 finalimg=cv2.bitwise_and(d1,d2) return finalimg #now apply function while cap.isOpened(): status,frame=cap.read() #continue image taker motionimg=img_diff(gray1,gray2,gray3) #replacig image frame gray1=gray2 gray2=gray3 gray3=cvv2.color(frame,cv2.COLOR_BG2GRAY) #passing live image to gray3 cv2.imshow('live',frame) cv2.imshow('motion',motionimg) cv2.waitkey(10) & 0xff == ord('q') :