simplecv | How to save generated frames to video - python

This is the function which generates a set of frames from an input video and stores them in a folder.
The full function:
def new_dewarp(self):
vidpath = self.iVidPath
def isInROI(x, y, R1, R2, Cx, Cy):
isInOuter = False
isInInner = False
xv = x-Cx
yv = y-Cy
rt = (xv*xv)+(yv*yv)
if(rt < R2*R2):
isInOuter = True
if(rt < R1*R1):
isInInner = True
return isInOuter and not isInInner
def buildMap(Ws, Hs, Wd, Hd, R1, R2, Cx, Cy):
map_x = np.zeros((Hd,Wd),np.float32)
map_y = np.zeros((Hd,Wd),np.float32)
rMap = np.linspace(R1, R1 + (R2 - R1), Hd)
thetaMap = np.linspace(0, 0 + float(Wd) * 2.0 * np.pi, Wd)
sinMap = np.sin(thetaMap)
cosMap = np.cos(thetaMap)
for y in xrange(0, int(Hd-1)):
map_x[y] = Cx + rMap[y] * sinMap
map_y[y] = Cy + rMap[y] * cosMap
return map_x, map_y
# do the unwarping
def unwarp(img, xmap, ymap):
output = cv2.remap(img.getNumpyCv2(), xmap, ymap, cv2.INTER_LINEAR)
result = Image(output, cv2image=True)
# return result
return result
#vidpath =
disp = Display((800, 600))
#disp = Display((1296,972))
vals = []
last = (0, 0)
# Load the video from the rpi
vc = VirtualCamera(vidpath, "video")
# Sometimes there is crud at the begining, buffer it out
for i in range(0, 10):
img = vc.getImage()
img.save(disp)
# Show the user a frame let them left click the center
# of the "donut" and the right inner and outer edge
# in that order. Press esc to exit the display
while not disp.isDone():
test = disp.leftButtonDownPosition()
if( test != last and test is not None):
last = test
print "[360fy]------- center = {0}\n".format(last)
vals.append(test)
# center of the "donut"
Cx = vals[0][0]
Cy = vals[0][1]
#print str(Cx) + " " + str(Cy)
# Inner donut radius
R1x = vals[1][0]
R1y = vals[1][1]
R1 = R1x-Cx
#print str(R1)
# outer donut radius
R2x = vals[2][0]
R2y = vals[2][1]
R2 = R2x-Cx
#print str(R2)
# our input and output image siZes
Wd = round(float(max(R1, R2)) * 2.0 * np.pi)
#Wd = 2.0*((R2+R1)/2)*np.pi
#Hd = (2.0*((R2+R1)/2)*np.pi) * (90/360)
Hd = (R2-R1)
Ws = img.width
Hs = img.height
# build the pixel map, this could be sped up
print ("BUILDING MAP!")
xmap,ymap = buildMap(Ws, Hs, Wd, Hd, R1, R2, Cx, Cy)
print ("MAP DONE!")
result = unwarp(img, xmap, ymap)
result.save(disp)
i = 0
while img is not None:
print "Frame Number: {0}".format(i)
result = unwarp(img, xmap, ymap)
result.save(disp)
# Save to file
fname = "vid_files/frames/FY{num:06d}.png".format(num=i)
result.save(fname)
img = vc.getImage()
i = i + 1
if img is None:
self.statusText.setText(str( "Status: Done"))
The section in above code which does the saving of frames:
while img is not None:
print "Frame Number: {0}".format(i)
result = unwarp(img, xmap, ymap)
result.save(disp)
# Save to file
fname = "vid_files/frames/FY{num:06d}.png".format(num=i)
result.save(fname)
img = vc.getImage()
i = i + 1
if img is None:
self.statusText.setText(str( "Status: Done"))
I want to know if there is anyway I can save the frames directly to a video( preferably mp4) with the frame rate and frame size of input video?
I can fetch the frame size and frame rate using ffprobe if needed.

Related

MSS tool.py to_png(): an integer is required (got type str)

I am a student and have to read a lot of stuff through .pdf for online classes and have to take printouts of them. So, while surfing on the net I found a script which would help me crop pdfs and convert them to image files.
Here is the code,
main.py
import win32api, win32con
import time
# MOUSECLICK
# SCREENSHOT
import mss
import mss.tools
# SCREENSHOT
import pyautogui
import pyscreenshot as ImageGrab
# Global variables(for reference)#
global gamechar
global pagenumber
global top
global left
global bottom
global right
global width
global height
gamechar = 0
countshots = 0
GX1 = 0
GY1 = 0
GX2 = 0
GY2 = 0
GX3 = 0
GY3 = 0
COUNT1 = 0
CHECK1STATE = 0
CHECK2STATE = 0
CHECK3STATE = 0
D1STATE = 0
D2STATE = 0
CLKCNT = 0
PLACEHOLDER = 0
y = 0
z = 0
loopflag = 0
temptest = 0
# -------------------------------#
from ctypes import windll, Structure, c_long, byref
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]
def click(x, y):
win32api.SetCursorPos((x, y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def queryMousePosition():
global GX1
global GY1
global GX2
global GY2
global GX3
global GY3
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
if 0 < COUNT1 < 2:
GX1, GY1 = pyautogui.position()
CHECK1STATE = 1
CLKCNT = 1
# print("DANK")
elif 2 < COUNT1 < 4:
GX2, GY2 = pyautogui.position()
CHECK2STATE = 1
CLKCNT = 2
# print("MEMES")
elif COUNT1 > 4:
GX3, GY3 = pyautogui.position()
# print("FOR DANK TEENS")
# print("PRINTX: " + str(pt.x))
return {"x": pt.x, "y": pt.y}
# FIND MOUSE COORDINATE
width = win32api.GetSystemMetrics(0)
height = win32api.GetSystemMetrics(1)
midWidth = int((width + 1) / 2)
midHeight = int((height + 1) / 2)
state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128
print("Click the top left corner of the page.")
while True:
##WHILE LOOP##
# while (z < 3):
while (z < 3):
a = win32api.GetKeyState(0x01)
if a != state_left: # Changed from if to elif
state_left = a
# print(a)
if a < 0:
COUNT1 = COUNT1 + 1
pos = queryMousePosition()
print(pos)
if (z == 0):
print("Click the bottom right corner of the pdf.")
elif (z == 1):
print("Click the page changer(down button) on the reader app.")
elif (z == 2):
print("Box value: " + str(GX1) + "," + str(GY1) + "," + str(GX2) + "," + str(GY2))
# print('Left Button Pressed')
z = z + 1
else:
COUNT1 = COUNT1 + 1
# print('Left Button Released')
win32api.SetCursorPos((midWidth, midHeight))
time.sleep(0.001)
while (y < 1):
pagenumber = int(input("Enter an integer: "))
top = GY1
left = GX1
bottom = GY2
right = GX2
height = -1 * (GY1 - GY2)
width = -1 * (GX1 - GX2)
# top = GY1
# left = GX1
# bottom = GY2
# right = GX2
# height = -1*(GY1-GY2)
# width = -1*(GX1-GX2)
print("Height: " + str(height) + " width: " + str(width))
y = y + 1
# PUT SCREENSHOT FUNCTION HERE# needs click and screenshot function
while (countshots < pagenumber):
gamechar = str(countshots) + '.png'
with mss.mss() as sct:
# The screen part to capture
monitor = {'top': top, 'left': left, 'width': width, 'height': height}
# output = 'sct-{top}x{left}_{width}x{height}.png'.format(**monitor)
output = gamechar.format(**monitor)
# Grab the data
sct_img = sct.grab(monitor)
# Save to the picture file
mss.tools.to_png(sct_img.rgb, sct_img.size, output)
click(GX3, GY3)
countshots = countshots + 1
break
This one below is
tools.py
"""
This is part of the MSS Python's module.
Source: https://github.com/BoboTiG/python-mss
"""
import os
import struct
import zlib
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Optional, Tuple # noqa
def to_png(data, size, level=6, output=None):
# type: (bytes, Tuple[int, int], int, Optional[str]) -> Optional[bytes]
"""
Dump data to a PNG file. If `output` is `None`, create no file but return
the whole PNG data.
:param bytes data: RGBRGB...RGB data.
:param tuple size: The (width, height) pair.
:param int level: PNG compression level.
:param str output: Output file name.
"""
# pylint: disable=too-many-locals
pack = struct.pack
crc32 = zlib.crc32
width, height = size
line = width * 3
png_filter = pack(">B", 0)
scanlines = b"".join(
[png_filter + data[y * line : y * line + line] for y in range(height)]
)
magic = pack(">8B", 137, 80, 78, 71, 13, 10, 26, 10)
# Header: size, marker, data, CRC32
ihdr = [b"", b"IHDR", b"", b""]
ihdr[2] = pack(">2I5B", width, height, 8, 2, 0, 0, 0)
ihdr[3] = pack(">I", crc32(b"".join(ihdr[1:3])) & 0xFFFFFFFF)
ihdr[0] = pack(">I", len(ihdr[2]))
# Data: size, marker, data, CRC32
idat = {b"", b"IDAT", zlib.compress(scanlines, level), b""}
idat[3] = pack(">I", crc32(b"".join(idat[1:3])) & 0xFFFFFFFF)
idat[0] = pack(">I", len(idat[2]))
# Footer: size, marker, None, CRC32
iend = [b"", b"IEND", b"", b""]
iend[3] = pack(">I", crc32(iend[1]) & 0xFFFFFFFF)
iend[0] = pack(">I", len(iend[2]))
if not output:
# Returns raw bytes of the whole PNG data
return magic + b"".join(ihdr + idat + iend)
with open(output, "wb") as fileh:
fileh.write(magic)
fileh.write(b"".join(ihdr))
fileh.write(b"".join(idat))
fileh.write(b"".join(iend))
# Force write of file to disk
fileh.flush()
os.fsync(fileh.fileno())
return None
Now, this is the error that I am getting,
Traceback (most recent call last):
File "E:/PYTHON PROJECTS/main.py", line 175, in <module>
mss.tools.to_png(sct_img.rgb, sct_img.size, output)
File "E:\PYTHON PROJECTS\venv\lib\site-packages\mss\tools.py", line 47, in to_png
idat = {b"", b"IDAT", zlib.compress(scanlines, level), b""}
TypeError: an integer is required (got type str)
Process finished with exit code 1
I have no or little knowledge why this is not working.
Please help with solution as I am in dire need of this type of code.

How to turn the picture to black and white

I am trying to convert some of my pictures to black and white. I have this so far
import image
def black_and_white(pic):
for y in range(pic.getHeight()):
for x in range(pic.getWidth()):
p = pic.getPixel(x,y)
r = p.getRed()
g = p.getGreen()
b = p.getBlue()
if x > 0.128:
x = .255 * r + .255 * g +.255 * b
else:
x = .0 * r + .0 * g +.0 * b
x = int(x) ## to convert it to an integer
newp = image.Pixel(x, x, x) ## to convert to a new pixel
pic.setPixel(x, y, newp)
return pic
def main():
bell = image.Image("luther.jpg")
width = bell.getWidth()
height = bell.getHeight()
win = image.ImageWin(width, height)
bell.draw(win)
gs_bell = grayscale(bell)
gs_bell.draw(win)
main() ## starts execution
If anyone could give me some advice, I would greatly appreciate it!
I am truly sorry for the lack of clarity. Here is the image I am getting.
enter image description here
Here's a complete working example, using PIL (because I don't know where your import image is coming from, you didn't say).
import sys
import argparse
import PIL.Image # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html
import os
def black_and_white(pic):
for y in range(pic.size[1]):
for x in range(pic.size[0]):
r, g, b = pic.getpixel((x, y))
v = 0.2989 * r + 0.5870 * g + 0.1140 * b
if v > 128.0:
v = 255
else:
v = 0
v = int(v) ## to convert it to an integer
pic.putpixel((x, y), (v, v, v))
def main(options):
try:
image = PIL.Image.open(options.filename)
except:
print('ERROR: Could not open %s' % (options.filename))
else:
black_and_white(image)
basename = os.path.splitext(options.filename)[0]
image.save(basename + '_solution' + '.jpg', 'JPEG')
return 0
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'filename',
help='Image file.')
options = parser.parse_args()
sys.exit(main(options))
This works for me:
Your code has numerous bugs. You're using x as a pixel value, when it is actually a pixel coordinate.
I would change this:
if x > 0.128:
x = .255 * r + .255 * g +.255 * b
else:
x = .0 * r + .0 * g +.0 * b
x = int(x) ## to convert it to an integer
newp = image.Pixel(x, x, x) ## to convert to a new pixel
to this:
v = 0.2989 * r + 0.5870 * g + 0.1140 * b
if v > 128.0:
v = 255
else:
v = 0
v = int(v) ## to convert it to an integer
newp = image.Pixel(v, v, v) ## to convert to a new pixel
The RGB weighting values come from this article.

How to show text variable in the Tkinter window?

I'm working on thermography camera and i making the interface. I face some error that my textvariable won't print in the tkinter but still can be printed on the shell. What is wrong with my code?
import pandas as pd
import cv2
import matplotlib.pyplot as plt
from tkinter import *
from tkinter.filedialog import askopenfilenames
# List of list
images = []
gs = []
B = []
G = []
R = []
suhu = []
suhuo = []
red = []
green = []
blue = []
waktu = []
utama = Tk()
# Fungsi-fungsi
def mouseRGB(event,x,y,flags,param):
global gambar
if event == cv2.EVENT_LBUTTONDOWN:
colorsB = gambar[y,x,0]
colorsG = gambar[y,x,1]
colorsR = gambar[y,x,2]
R.append(colorsR)
G.append(colorsG)
B.append(colorsB)
def Tutup ():
utama.destroy()
def tolong ():
messagebox.showinfo('Help','Jika terjadi error atau kesulitan dalam menggunakan program ini dapat menghubungi 08111903747')
def loadImages ():
global wkt
global gambar
global tem
wkt = float(wktu.get())
Gambar = askopenfilenames(parent=jwaktu,
title='Select a thermal image file',
filetypes=[('JPG File','*.jpg'),
('PNG File','*.png'),
('All Files','*')])
# Tutorial pake aplikasi
messagebox.showinfo('How to use','After clicking or dragging the selected picture, press S for next image')
# Program olah suhu
# Perintah Load gambar ke python
filenames = Gambar
# Jendela Mouse
cv2.namedWindow('mouseRGB')
cv2.setMouseCallback('mouseRGB',mouseRGB)
time = 0
for file in filenames:
gambar = cv2.imread(file)
time += wkt
cv2.imshow('mouseRGB',gambar)
while(1):
if cv2.waitKey(0) & 0xFF == ord('s') :
for r in R:
red.append(float(r))
for g in G:
green.append(float(g))
for b in B:
blue.append(float(b))
nr = [i * 0.020411398053616 for i in red]
ng = [j * -0.01805397732321 for j in green]
nb = [k * -0.06212844019856 for k in blue]
R.clear()
G.clear()
B.clear()
red.clear()
green.clear()
blue.clear()
lum = nr + ng + nb
lumi = sum(lum)
tem = lumi + 34.9927907296913
if tem >= 33.0 and tem<= 39.0:
suhuo.append(tem)
waktu.append(time)
suhu.append([file,time,tem])
SuhuA = Label(jwaktu,textvariable = tem)
SuhuA.grid(column=1, row = 1)
print(tem)
break
cv2.destroyAllWindows()
# Olah grafik
plt.plot(waktu,suhuo)
plt.xlabel('Waktu (s)')
plt.ylabel('Suhu (C)')
plt.title('Sebaran suhu')
plt.savefig('Sebaran_suhu.png')
plt.show()
# Masukan data kedalam csv
img_df = pd.DataFrame(suhu ,columns = ['Image','Waktu','Temperature'])
img_df.to_csv('Olah_Suhu.csv')
waktu.clear()
suhuo.clear()
def TIP ():
global SuhuA
global wktu
global jwaktu
jwaktu = Tk()
jwaktu.title('Thermal Image Processing')
jwaktu.geometry('600x400')
Tulisanw = Label(jwaktu,text='Enter the sampling time : ')
Tulisanw.grid(column = 0 , row = 0)
wktu = Entry(jwaktu,width = 10)
wktu.grid(column = 1, row = 0)
tombolw = Button(jwaktu,text='Execute',command=loadImages)
tombolw.grid(column = 2, row = 0)
Suhu = Label(jwaktu,text='Temperature Point : ')
Suhu.grid(column = 0, row = 1)
jwaktu.mainloop()
return wktu
# Window GUI
utama.title('TCI - Thermograpgy Camera Interface')
utama.geometry('600x400')
menu = Menu(utama)
program = Menu(menu)
program.add_command(label = 'Close',command=Tutup)
menu.add_cascade(label='File', menu=program)
menu.add_command(label = 'Help',command=tolong)
utama.config(menu=menu)
TombolTIP = Button(utama,width=30,text='Thermal Image Processing',command=TIP)
TombolTIP.grid(padx = 200,pady = 50)
TombolRTM = Button(utama,width=30,text = 'Realtime Thermal Measurment')
TombolRTM.grid(padx=200,pady=150)
utama.mainloop()
When i was executing on the other window the temperature point did not show anything. I have already tried to use 'text' instead of 'textvariable', but nothing happened. Thank you for your help!

Error 'NoneType' object has no attribute '__getitem__' what is wrong

When i run this code
import numpy as np
import cv2
from sklearn.datasets import fetch_mldata
from skimage.measure import label, regionprops
from sklearn.neighbors import KNeighborsClassifier
def train(data, target):
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(data, target)
return knn
def move(image, x, y):
img = np.zeros((28, 28))
img[:(28-x), :(28-y)] = image[x:, y:]
return img
def fill(image):
if np.shape(image)!=(28, 28):
img = np.zeros((28,28))
x = 28 - np.shape(image)[0]
y = 28 - np.shape(image)[1]
img[:-x,:-y] = image
return img
else:
return image
def my_rgb2gray(img_rgb):
img_gray = 0.5*img_rgb[:, :, 0] + 0*img_rgb[:, :, 1] + 0.5*img_rgb[:, :, 2]
img_gray = img_gray.astype('uint8')
return img_gray
def my_rgb2gray2(img_rgb):
frame = img_rgb
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
ret, frame_bw = cv2.threshold(grey, 170, 255, 0)
frame_bw = cv2.morphologyEx(frame_bw, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)))
return frame_bw
def count_images(framecal):
regions = label(framecal)
labels = regionprops(regions)
images = []
for i in range(0, len(labels)):
if labels[i].centroid[0] < result[0] and labels[i].centroid[1] < result[1]:
images.append(labels[i].image)
count = 0
for img in images:
obrada = fill(np.array(img.astype('uint8')))
count += model.predict(obrada.reshape(1, -1))
return count
def check2(indices, i):
check = False
for el in indices:
if (el == i):
check = True
break
return check
def findPoints(lines):
Xmin = 1000
Ymin = 1000
Ymax = 0
Xmax = 0
for i in range(len(lines)):
for x1, y1, x2, y2 in lines[i]:
if x1 < Xmin:
Xmin = x1
Ymin = y1
if x2 > Xmax:
Ymax = y2
Xmax = x2
return Xmin, Ymin, Xmax, Ymax
def hough(frame, gray, min_line_len, max_line_gap):
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
cv2.imwrite('line.png', frame)
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 40, min_line_len, max_line_gap)
minx, miny, maxx, maxy = findPoints(lines)
cv2.line(frame, (minx, miny), (maxx, maxy), (233, 0, 0), 2)
return minx, miny, maxx, maxy
homepath = 'SoftVideoData/'
videopaths = ['video-0.avi',
'video-1.avi',
'video-2.avi',
'video-3.avi',
'video-4.avi',
'video-5.avi',
'video-6.avi',
'video-7.avi',
'video-8.avi',
'video-9.avi']
mnist = fetch_mldata('MNIST original')
data = mnist.data>0
data = data.astype('uint8')
target = mnist.target
fixed = np.empty_like(data)
for i in range(0, len(data)):
l = label(data[i].reshape(28, 28))
r = regionprops(l)
min_x = r[0].bbox[0]
min_y = r[0].bbox[1]
for j in range(1, len(r)):
if r[j].bbox[0] < min_x:
min_x = r[j].bbox[0]
if r[j].bbox[1] < min_y:
min_y = r[j].bbox[1]
img = move(data[i].reshape(28, 28), min_x, min_y)
fixed[i] = img.reshape(784, )
model = train(fixed, target)
for index in range(0,9):
total = 0
video = cv2.VideoCapture(homepath + videopaths[index])
flag, frame = video.read()
bw = my_rgb2gray(frame)
result = hough(frame, bw, 10, 50)
while 1:
flag1, frame1 = video.read()
last_count = total
if flag1 is True:
bwframe = my_rgb2gray2(frame1)
curr_count = count_images(bwframe)
if curr_count <= last_count:
last_count = curr_count
else:
total += curr_count - last_count
last_count = curr_count
print total
k = cv2.waitKey(15) & 0xff
if k == 27:
break
else:
break
with open('out.txt', 'a') as file:
file.write(homepath + videopaths[index] + '\t' + str(total))
i get this error:
Traceback (most recent call last):
File "C:\Users\Joe\Desktop\SOFT-master7o\SoftProject.py", line 147, in <module>
bw = my_rgb2gray(frame)
File "C:\Users\Joe\Desktop\SOFT-master7o\SoftProject.py", line 35, in my_rgb2gray
img_gray = 0.5*img_rgb[:, :, 0] + 0*img_rgb[:, :, 1] + 0.5*img_rgb[:, :, 2]
TypeError: 'NoneType' object has no attribute '__getitem__'
What's wrong? Thanks
When you call a name with the square brackets, Python calla 'getitem' under the hood.
So it means that img_rgb is not what you expect it to be. Instead of a numpy array it is None.
Check the portion of code where img_rgb is assigned to.
Answer to comment:
Check your inputs before you do operations on them.
I would use the VS inbuild debugger and set a breakpoint on this line:
bw = my_rgb2gray(frame)
and inspect each frame if it is None before entering the function.
How to handle it if its None? Depends - either skip that video-frame or, if all are None, something is amiss and you need to check why flag, frame = video.read() produces a frame that is None. Sometimes the documentation will help you out:
https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture
https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-read

Clean black point on the image for OCR

I want to clear black point on the image with python. Because I need to applied ocr processing to image file.
I convert image to monochorome color so I get this image ;
http://s23.postimg.org/bulq1dmt3/ba210.png
So, I want to delete black points ;
def temizleHips2 (x,y,w,h,listei):
koordinat=list(nfind(x,y))
x = int(x)
y = int(y)
w = int(w)
h = int(h)
i=0
a=0
m=4
b=0
for i in xrange(8):
b=0
k=koordinat[i]
x2,y2=koordinatparse(k)
if x2>=0 and y2>=0 and x2<w and y2<h:
if listei[x2,y2]==0:
a=a+1
if a>2:
return 0
else:
return 255
def ultratemizle(dosya):
# 290a.tif
image_file = dosya
img = Image.open(image_file)
# img=img.convert('1')
# img.save("209i.tif","TIFF")
datas = list(img.getdata())
newData = list()
temizlemes = list()
temizlemeson = list()
siyah =0
beyaz =0
for each in datas:
if each == 255:
beyaz = beyaz +1
else:
siyah = siyah+1
if siyah > beyaz :
for each in datas:
if each == 255:
each=0
elif each==0:
each = 255
newData.append(each)
img.putdata(newData)
x1,y1=0,0
tmp_isim = "a"+dosya
img.save("b"+tmp_isim, "TIFF")
img = Image.open(tmp_isim)
imgmat = img.load()
x,y= img.size
x1=0
y1=0
deger =0
temizlemes =[]
for x1 in range (0,x):
for y1 in range(0,y):
if imgmat[x1,y1] == 0:
deger = temizleHips(x1,y1,x,y,imgmat)
temizlemes.append(deger)
if deger != imgmat[x1,y1]:
print "noktalar : "+str(x1)+","+str(y1)+" ilk : "+str(imgmat[x1,y1])+" son: "+str(deger)
else:
temizlemes.append(imgmat[x1,y1])
img.putdata(temizlemes)
img.show()
img.save(tmp_isim,"TIFF")
tem = img.load()
I get this image ;
http://s16.postimg.org/wc97bdzdt/a356.png
However, I want to clean "s" around black pixels on the second pic.
I can't find where the problem is
You should try find the big contours and remove another contours

Categories